使用python3.6在Ubuntu中进行了一项使用Chrome headless浏览器的工做, 在此记录下遇到的问题以及解决方法.
参考 unning-selenium-with-headless-chromepython
参考 Installing ChromeDriver on Ubuntulinux
from selenium.webdriver.chrome.options import Options chrome_options = Options() 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下若是系统不支持可视化不加这条会启动失败 chrome_options.binary_location = r'/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary' #手动指定使用的浏览器位置
须要在打开浏览器后, 获取浏览器的command_executor url
, 以及session_id
web
opener.command_executor._url, opener.session_id #opener为webdriver对象
以后经过remote
方式连接chrome
from selenium import webdriver opener = webdriver.Remote(command_executor=_url,desired_capabilities={}) #_url为上面的_url opener.close() #这时会打开一个全新的浏览器对象, 先把新的关掉 opener.session_id = session_id #session_id为上面的session_id
以后对opener
的任何操做都会反映在以前的浏览器上.浏览器
--headless
这样的浏览器参数from selenium.webdriver.common.desired_capabilities import DesiredCapabilities capabilities = DesiredCapabilities.CHROME capabilities.setdefault('chromeOptions', {'args':['--headless', '--disable-gpu']})
chromedriver not in PATH
初始化的时候, 传入chromedriver绝对路径安全
opener = webdriver.Chrome(r'/usr/local/bin/chromedriver', chrome_options=chrome_options)
opener.get_cookies()
opener.add_cookie(cookie) #须要先访问该网站产生cookies后再进行覆写
opener.implicitly_wait(30) #30是最长等待时间
cookie
偏向使用js函数来执行网络
opener.execute_script('''window.open("http://baidu.com","_blank");''')
有些时候页面在你点击后会异步进行请求, 完成一些操做, 这时可能就会生成输出数据的url, 只要抓到这个url就能够跳过token验证等安全监测, 直接得到数据.session
script = "var performance = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance || {}; var network = performance.getEntries() || {}; return network;" performances = opener.execute_script(script)
script里是js代码, 通常用来进行性能检查, 网络请求情况, 使用selenium执行这段js就能够得到全部的请求信息.app
おわり.