python+selenium+chrome批量文件下载并自动创建文件夹实例
作者:滑冰选手库里 发布时间:2022-09-14 09:56:42
实现效果:通过url所绑定的关键名创建目录名,每次访问一个网页url后把文件下载下来
代码:
其中 data[i][0]、data[i][1] 是代表 关键词(文件保存目录)、网站链接(要下载文件的网站)
def getDriverHttp():
for i in range(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'<a href="#" rel="external nofollow" onclick="(.*?)" cssclass="xz_pic">', driver.page_source, re.S)
print(len(info2))
for js in info2:
driver.execute_script(js)
def main():
getDriverHttp()
注意:python 使用selenium下载文件时,chrome会提示是否下载多个文件(Download multiple files)
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:
pip install numpy
pip install easydict
pip install yaml
就可以了。
然后定义配置类config.py:
import numpy as np
from easydict import EasyDict as edict
import yaml
# 创建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):
"""Merge config dictionary a into config dictionary b, clobbering the
options in b whenever they are also specified in a.
"""
if type(a) is not edict:
return
for k, v in a.items():
# a must specify keys that are in b
if k not in b:
raise KeyError('{} is not a valid config key'.format(k))
# the types must match, too
old_type = type(b[k])
if old_type is not type(v):
if isinstance(b[k], np.ndarray):
v = np.array(v, dtype=b[k].dtype)
else:
raise ValueError(('Type mismatch ({} vs. {}) '
'for config key: {}').format(type(b[k]),
type(v), k))
# recursively merge dicts
if type(v) is edict:
try:
_merge_a_into_b(a[k], b[k])
except:
print(('Error under config key: {}'.format(k)))
raise
else:
b[k] = v
# 自动加载yaml文件
def cfg_from_file(filename):
"""Load a config file and merge it into the default options."""
with open(filename, 'r', encoding='utf-8') as f:
yaml_cfg = edict(yaml.load(f))
_merge_a_into_b(yaml_cfg, __C)
使用的时候很简单,main.py:
from config import cfg_from_file
from config import cfg
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文件中只要from config import cfg就可以使用配置文件。
第二种 基于Class实现
这种基于普通的python对象实现的,创建config2.py:
class Config:
def __init__(self):
self.name = 'xingoo-config2'
self.age = 100
使用的时候直接创建一个新的对象,如何python模块之间需要引用这个变量,那么需要把配置对象传过去:
import config2 as config2
cfg2 = config2.Config()
print(cfg2.name)
print(cfg2.age)
输出为:
xingoo-config2
100
总结
第二种方法简单粗暴...不过每次传递参数也是很蛋疼。还是喜欢第一种方式。
来源:https://blog.csdn.net/weixin_40096730/article/details/88978151
猜你喜欢
- 多表操作 在一个数据库中,可能存在多个表,这些表都是相互关联的。我
- 排序排序是指以特定格式排列数据。排序算法指定以特定顺序排列数据的方式。最常见的顺序是数字或字典顺序。在 Numpy 中,我们可以使用库中提供
- np.arange 步长0.1问题两个小测试:1)count输出什么?import numpy as np y_m
- 虽然 prometheus 已有大量可直接使用的 exporter 可供使用,以满足收集不同的监控指标的需要。例如,node exporte
- 1:在终端下:mysql -V。 以下是代码片段:[shengting@login ~]$ mysql -Vmysql Ver 14.7 D
- 质数(Prime number),又称素数,指在大于1的自然数中,除了1和该数自身外,无法被其他自然数整除的数(也可定义为只有1与该数本身两
- 机器学习之随机森林,供大家参考,具体内容如下1、Bootstraping(自助法)  
- 网上有很多关于Python+opencv人脸检测的例子,并大都附有源程序。但是在实际使用时依然会遇到这样或者那样的问题,在这里给出常见的两种
- 本文实例讲述了Python简单实现自动删除目录下空文件夹的方法。分享给大家供大家参考,具体如下:总是发现电脑用上一段时间,各种软件生成各种目
- 本文实例为大家分享了python+openCV利用摄像头实现人员活动检测的具体代码,供大家参考,具体内容如下1.前言最近在做个机器人比赛,其
- 前言:在Python中,如果我们想要在遍历一组数据的过程中,对这组数据进行修改,通常会出现许多问题,例如对列表进行上述操作时, 会忽略部分数
- pydantic-resolve 解决嵌套数据结构的生成和其他方案的比较pydantic-resolve和GraphQL相比GraphQL的
- 保存时代码如下:figure_corp = figure.crop( (32*rate/2, 32*rate/2, 32-32*rate/2
- 本文实例讲述了Python函数的返回值、匿名函数lambda、filter函数、map函数、reduce函数用法。分享给大家供大家参考,具体
- python打印当前文件的绝对路径并解决打印为空获取当前文件所在路径主要使用os.path.dirname(os.path.abspath(
- python面向对象编程入门,我们需要不断学习进步"""抽象工厂模式的实现"""
- 一、介绍这篇文档旨在介绍如何安装配置基于2台服务器的MySQL集群。并且实现任意一台服务器出现问题或宕机时MySQL依然能够继续运行。虽然这
- 求:机房、线上有多台主机,为了保障安全,需要定期修改密码。若手动修改,费时费力易出错。程序应该满足如下需求 :1、在现有的excel密码表格
- 一.图像量化处理原理量化(Quantization)旨在将图像像素点对应亮度的连续变化区间转换为单个特定值的过程,即将原始灰度图像的空间坐标
- 前言在几周前,我开始工作于一个证券投资组合网站。虽然我只能使用 React 完成整个网站,但我决定使用 Go 来创建一个可以处理某些任务(例