Python无头爬虫下载文件的实现
2020-04-03 12:04
585 查看
有些页面并不能直接用requests获取到内容,会动态执行一些js代码生成内容。这个文章主要是对付那些特殊页面的,比如必须要进行js调用才能下载的情况。
安装chrome
wget [https://dl.google.com/linux/direct/google-chrome-stable\_current\_x86\_64.rpm](https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm) yum install ./google-chrome-stable\_current\_x86\_64.rpm yum install mesa-libOSMesa-devel gnu-free-sans-fonts wqy-zenhei-fonts
安装chromedriver
淘宝源(推荐)
wget http://npm.taobao.org/mirrors/chromedriver/2.41/chromedriver_linux64.zip unzip chromedriver\_linux64.zip move chromedriver /usr/bin/ chmod +x /usr/bin/chromedriver
感谢这篇博客
上述步骤可以选择适合自己的版本下载,注意:chrome和chrome driver必须是匹配的版本,chrome driver会备注支持的chrome版本号。
实战操作
需要引入的库
from selenium import webdriver from time import sleep from selenium.webdriver.chrome.options import Options from selenium.common.exceptions import NoSuchElementException
chrome启动设置
chrome_options = Options() chrome_options.add_argument('--no-sandbox')#解决DevToolsActivePort文件不存在的报错 chrome_options.add_argument('window-size=1920x3000') #指定浏览器分辨率 chrome_options.add_argument('--disable-gpu') #谷歌文档提到需要加上这个属性来规避bug chrome_options.add_argument('--hide-scrollbars') #隐藏滚动条, 应对一些特殊页面 chrome_options.add_argument('blink-settings=imagesEnabled=false') #不加载图片, 提升速度 chrome_options.add_argument('--headless') #浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
同样感谢上面的博客
设置额外参数,比如下载不弹窗和默认下载路径
prefs = {'profile.default_content_settings.popups': 0, 'download.default_directory': './filelist'} chrome_options.add_experimental_option('prefs', prefs)
初始化驱动
cls.driver=webdriver.Chrome(options=chrome_options)
退出驱动
cls.driver.quit()
请求一个url
cls.driver.get(url)
执行指定js代码
cls.driver.execute_script('console.log("helloworld")')
查找指定元素
subtitle = cls.driver.find_element_by_class_name("fubiaoti").text
到此这篇关于Python无头爬虫下载文件的实现的文章就介绍到这了,更多相关Python无头爬虫下载文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
您可能感兴趣的文章:
相关文章推荐
- Python爬虫框架scrapy实现的文件下载功能示例
- python 实现文件下载
- python_ftplib实现通过FTP下载文件
- python实现上传下载文件功能
- github 资源文件下载(python 爬虫)
- python实现socket上传下载文件-进度条显示
- python paramiko实现多线程远程执行命令、多线程远程上传文件、多线程远程下载文件
- mac os平台使用python爬虫自动下载巨潮网络文件
- python实现网站的js文件下载
- python实现爬虫下载美女图片
- 使用Python下载歌词并嵌入歌曲文件中的实现代码
- 和我一起使用Python的bottle来实现文件的上传和下载(使用post方法)
- 【Python】python3实现网页爬虫下载图片
- Python爬虫实现百度图片自动下载
- python实现下载文件的三种方法
- python实现从ftp服务器下载文件的方法
- Python实现批量下载文件
- python实现断点续传下载文件
- Python+django实现文件下载
- python实现进度条--主要用在上传下载文件