python+selenium+chrome批量文件下载并自动创建文件夹实例
实现效果:通过url所绑定的关键名创建目录名,每次访问一个网页url后把文件下载下来
代码:
其中data[i][0]、data[i][1]是代表关键词(文件保存目录)、网站链接(要下载文件的网站)
defgetDriverHttp():
foriinrange(reCount):
#创建Chrome浏览器配置对象实例
chromeOptions=webdriver.ChromeOptions()
#设定下载文件的保存目录为d盘的tudi目录,
#如果该目录不存在,将会自动创建
prefs={"download.default_directory":"e:\\tudi\\{0}".format(data[i][0]),"profile.default_content_setting_values.automatic_downloads":1}
#将自定义设置添加到Chrome配置对象实例中
chromeOptions.add_experimental_option("prefs",prefs)
#启动带有自定义设置的Chrome浏览器
#driver=webdriver.Chrome(executable_path="e:\\chromedriver",chrome_options=chromeOptions)
driver=webdriver.Chrome(chrome_options=chromeOptions)
driver.get(data[i][1])
info2=re.findall(r'',driver.page_source,re.S)
print(len(info2))
forjsininfo2:
driver.execute_script(js)
defmain():
getDriverHttp()
注意:python使用selenium下载文件时,chrome会提示是否下载多个文件(Downloadmultiplefiles)
prefs={"download.default_directory":"e:\\tudi\\{0}".format(data[i][0]),"profile.default_content_setting_values.automatic_downloads":1}
设置允许多个文件下载。
补充知识:python项目实现配置统一管理的操作
一个比较大的项目总是会涉及到很多的参数,最好的方法就是在一个地方统一管理这些参数。最近看了不少的python项目,总结了两种很有意思的配置管理方法。
第一种基于easydict实现的配置管理
首先需要安装numpy、easydict以及yaml:
pipinstallnumpy
pipinstalleasydict
pipinstallyaml
就可以了。
然后定义配置类config.py:
importnumpyasnp
fromeasydictimportEasyDictasedict
importyaml
#创建dict
__C=edict()
cfg=__C
#定义配置dict
__C.dev=edict()
__C.dev.name='dev-xingoo'
__C.dev.age=20
__C.test=edict()
__C.test.name='test-xingoo'
__C.test.age=30
#内部方法,实现yaml配置文件到dict的合并
def_merge_a_into_b(a,b):
"""Mergeconfigdictionaryaintoconfigdictionaryb,clobberingthe
optionsinbwhenevertheyarealsospecifiedina.
"""
iftype(a)isnotedict:
return
fork,vina.items():
#amustspecifykeysthatareinb
ifknotinb:
raiseKeyError('{}isnotavalidconfigkey'.format(k))
#thetypesmustmatch,too
old_type=type(b[k])
ifold_typeisnottype(v):
ifisinstance(b[k],np.ndarray):
v=np.array(v,dtype=b[k].dtype)
else:
raiseValueError(('Typemismatch({}vs.{})'
'forconfigkey:{}').format(type(b[k]),
type(v),k))
#recursivelymergedicts
iftype(v)isedict:
try:
_merge_a_into_b(a[k],b[k])
except:
print(('Errorunderconfigkey:{}'.format(k)))
raise
else:
b[k]=v
#自动加载yaml文件
defcfg_from_file(filename):
"""Loadaconfigfileandmergeitintothedefaultoptions."""
withopen(filename,'r',encoding='utf-8')asf:
yaml_cfg=edict(yaml.load(f))
_merge_a_into_b(yaml_cfg,__C)
使用的时候很简单,main.py:
fromconfigimportcfg_from_file
fromconfigimportcfg
cfg_from_file('config.yml')
print(cfg.dev.name)
print(cfg.test.name)
同级目录下创建配置文件config.yaml
dev:
name:xingoo-from-yml
输出:
xingoo-from-yml
test-xingoo
总结
这样的好处就是在任何的Python文件中只要fromconfigimportcfg就可以使用配置文件。
第二种基于Class实现
这种基于普通的python对象实现的,创建config2.py:
classConfig: def__init__(self): self.name='xingoo-config2' self.age=100
使用的时候直接创建一个新的对象,如何python模块之间需要引用这个变量,那么需要把配置对象传过去:
importconfig2asconfig2 cfg2=config2.Config() print(cfg2.name) print(cfg2.age)
输出为:
xingoo-config2
100
总结
第二种方法简单粗暴...不过每次传递参数也是很蛋疼。还是喜欢第一种方式。
以上这篇python+selenium+chrome批量文件下载并自动创建文件夹实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。