有些页面并不能直接用requests获取到内容,会动态执行一些js代码生成内容。这个文章主要是对付那些特殊页面的,好比必需要进行js调用才能下载的状况。html
1.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) 2.yum install ./google-chrome-stable\_current\_x86\_64.rpm 3.yum install mesa-libOSMesa-devel gnu-free-sans-fonts wqy-zenhei-fonts
1.淘宝源(推荐) wget http://npm.taobao.org/mirrors/chromedriver/2.41/chromedriver_linux64.zip 2.unzip chromedriver\_linux64.zip 3.move chromedriver /usr/bin/ 4.chmod +x /usr/bin/chromedriver
感谢这篇博客linux
上述步骤能够选择适合本身的版本下载,注意:chrome和chrome driver必须是匹配的版本,chrome driver会备注支持的chrome版本号。web
须要引入的库chrome
from selenium import webdriver from time import sleep from selenium.webdriver.chrome.options import Options from selenium.common.exceptions import NoSuchElementException
chrome启动设置npm
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下若是系统不支持可视化不加这条会启动失败
一样感谢上面的博客浏览器
设置额外参数,好比下载不弹窗和默认下载路径less
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)
ide
退出驱动cls.driver.quit()
ui
请求一个urlcls.driver.get(url)
google
执行指定js代码cls.driver.execute_script('console.log("helloworld")')
查找指定元素subtitle = cls.driver.find_element_by_class_name("fubiaoti").text