python+selenium+chrome批量文件下载并自动创建文件夹实例


Posted in Python onApril 27, 2020

实现效果:通过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

总结

第二种方法简单粗暴...不过每次传递参数也是很蛋疼。还是喜欢第一种方式。

以上这篇python+selenium+chrome批量文件下载并自动创建文件夹实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
浅谈python类属性的访问、设置和删除方法
Jul 25 Python
基于Python代码编辑器的选用(详解)
Sep 13 Python
python去除字符串中的换行符
Oct 11 Python
Python之web模板应用
Dec 26 Python
widows下安装pycurl并利用pycurl请求https地址的方法
Oct 15 Python
在Python中分别打印列表中的每一个元素方法
Nov 07 Python
python队列Queue的详解
May 10 Python
在Python中COM口的调用方法
Jul 03 Python
快速解决vue.js 模板和jinja 模板冲突的问题
Jul 26 Python
python 使用socket传输图片视频等文件的实现方式
Aug 07 Python
Python Pandas对缺失值的处理方法
Sep 27 Python
Python使用for生成列表实现过程解析
Sep 22 Python
解决pycharm编辑区显示yaml文件层级结构遇中文乱码问题
Apr 27 #Python
Python使用Pyqt5实现简易浏览器(最新版本测试过)
Apr 27 #Python
python读取yaml文件后修改写入本地实例
Apr 27 #Python
基于SpringBoot构造器注入循环依赖及解决方式
Apr 26 #Python
Python判断字符串是否为空和null方法实例
Apr 26 #Python
如何将PySpark导入Python的放实现(2种)
Apr 26 #Python
基于python实现对文件进行切分行
Apr 26 #Python
You might like
php 过滤英文标点符号及过滤中文标点符号代码
2014/06/12 PHP
CI框架数据库查询之join用法分析
2016/05/18 PHP
php中isset与empty函数的困惑与用法分析
2019/07/05 PHP
laravel框架使用FormRequest进行表单验证,验证异常返回JSON操作示例
2020/02/18 PHP
关于javascript DOM事件模型的两件事
2010/07/22 Javascript
js判断生效时间不得大于失效时间的思路及代码
2013/04/23 Javascript
详解用原生JavaScript实现jQuery的某些简单功能
2016/12/19 Javascript
vue.js+Element实现表格里的增删改查
2017/01/18 Javascript
JavaScript中在光标处插入添加文本标签节点的详细方法
2017/03/22 Javascript
探究react-native 源码的图片缓存问题
2017/08/24 Javascript
AngularJS实现的select二级联动下拉菜单功能示例
2017/10/25 Javascript
JS双向链表实现与使用方法示例(增加一个previous属性实现)
2019/01/31 Javascript
怎么理解wx.navigateTo的events参数使用详情
2020/05/18 Javascript
[57:59]EG vs Secret 2018国际邀请赛淘汰赛BO3 第一场 8.22
2018/08/23 DOTA
[43:47]完美世界DOTA2联赛PWL S3 LBZS vs Phoenix 第一场 12.09
2020/12/11 DOTA
flask中使用SQLAlchemy进行辅助开发的代码
2013/02/10 Python
python中字典dict常用操作方法实例总结
2015/04/04 Python
Pycharm学习教程(1) 定制外观
2017/05/02 Python
Python即时网络爬虫项目启动说明详解
2018/02/23 Python
django缓存配置的几种方法详解
2018/07/16 Python
python 读取竖线分隔符的文本方法
2018/12/20 Python
你还在@微信官方?聊聊Python生成你想要的微信头像
2019/09/25 Python
tensorflow 固定部分参数训练,只训练部分参数的实例
2020/01/20 Python
python安装读取grib库总结(推荐)
2020/06/24 Python
Win10下配置tensorflow-gpu的详细教程(无VS2015/2017)
2020/07/14 Python
世界上最大的巴士旅游观光公司:Big Bus Tours
2016/10/20 全球购物
尤为Wconcept中国官网:韩国设计师品牌服饰
2019/01/10 全球购物
澳大利亚最好的电动自行车:Leon Cycle
2020/12/19 全球购物
大学生的自我鉴定范文
2014/01/21 职场文书
电工工作职责范本
2014/02/22 职场文书
保护水资源的标语
2014/06/17 职场文书
中专毕业生的自荐书
2014/07/01 职场文书
承兑汇票延期证明
2015/06/23 职场文书
写自招自荐信的绝招!
2019/04/19 职场文书
如何书写授权委托书?
2019/06/25 职场文书
python 自动刷新网页的两种方法
2021/04/20 Python