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


猜你喜欢
- lambda函数是一种小的匿名函数。lambda语法lambda函数:lambda [arg1 [,arg2,...[,argn]]] :
- 很多小伙伴都会有这样的问题,说一个ip地址十分钟内之内注册一次,用来防止用户来重复注册带来不必要的麻烦逻辑:取ip,在数据库找ip是否存在,
- 前言第一次用mysql,打开mysql的图形化界面要连接时,出现2003错误。究其原因,可能是mysql的服务没有启动。本文章主要围绕这个解
- 在数据存储过多时,我们会选择清除,不过有时候也需要找回一些我们之前删掉的数据。有的小伙伴可能会使用不同的方法分别完成,那么今天小编带来的_d
- Flask Web开发实战学习笔记Flask简介Flask是使用Python编写的Web微框架。Web框架可以让我们不用关 心底层的请求响应
- 在日常生活中总是有给图像分类的场景,比如垃圾分类、不同场景的图像分类等;今天的文章主要是基于图像识别场景进行模型构建。图像识别是通过 Pyt
- 如下所示:df = df[df['cityname']==u'北京市']记得,如果用的python2,一定要
- 9月23,Django 发布了2.0a1版本,这是一个 feature freeze 版本,如果没有什么意外的话,2.0正式版不会再增加新的
- 本文实例为大家分享了js实现直播点击飘心效果的具体代码,供大家参考,具体内容如下<!DOCTYPE html><html&
- 国外的空间和我们国内的空间使用的语言系统一般不一样,所以在网页程序上时如果处理不当很容易出现乱码,看了让人摸不着头脑。所以我们在编写程序时就
- 01 实现背景1、PHPdict.txt,一个文本文件,包含可能的敏感目录后缀2、HackRequests模块,安全测试人员专用的类Requ
- PyCharm最近在用PyCharm的时候运行结果总是在Console里输出,而不是在run输出,下面列出解决方法1.点击工具栏run,再点
- 以下代码已经在SQLServer2008上的示例数据库测试通过问题一:如何为数据进行加密与解密,避免使用者窃取机密数据? 对于一些敏感数据,
- 如下所示:import pandas as pddf = pd.DataFrame({'性别' : ['男'
- 背景前段时间写了一个自动化安装 MySQL 的程序,其中有一个环节就是动态的渲染 my.cnf 文件;总的解决方案就是像 Django 渲染
- 边缘检测一般是识别目标图像中亮度变化明显的像素点. 因为显著变化的像素点通常反映了图像变化比较重要的地方.1. Canny 边缘检测理论Ca
- python字典怎么排序?定义一个字典类型mydict = {2: '小路', 3: '黎明', 1:
- 工欲善其事,必先利其器。作为更专业的前端工程师,我们需要强劲的IDE协助我们写出规范、美观、漂亮的JavaScript代码,首先要作的就是对
- 由于客户提供的是excel文件,在使用时期望使用csv文件格式,且对某些字段内容需要做一些处理,如从某个字段中固定的几位抽取出来,独立作为一
- 丢弃现有MySQL的表是很容易的。但是需要非常小心,删除任何现有的一个表后将无法恢复,因为数据丢失。语法:下面是通用的SQL语法丢弃(删除)