linux 安装 Headless Chrome

来源:互联网 发布:王者荣耀kda最新算法 编辑:程序博客网 时间:2024/05/23 17:37

前言

公司的爬虫项目使用了selenium+phantomjs,这个做过爬虫的应该都用过,但是缺点也很明显,慢,占用资源等,本身还有很多小坑就不一一列举了

后来无意中发现了headless,
参考这篇文章:https://intoli.com/blog/making-chrome-headless-undetectable/

经过安装测试,效果确实比phantomjs好很多,目前已有的资料都是使用nodejs,python相关的资料不多,只能等大佬们整理了。

这里记录一下安装的过程

安装chrome

需要V59以上版本
下载地址:https://www.landiannews.com/archives/36966.html

下载driver

selenium调用需要使用到
下载地址:https://sites.google.com/a/chromium.org/chromedriver/downloads

安装调试

下载安装chromedriver

mkdir chromecd chromewget https://chromedriver.storage.googleapis.com/2.31/chromedriver_linux64.zip unzip chromedriver_linux64.zip cd vi .bashrc #添加环境变量export PATH=/home/username/chrome:$PATH #在最后一行添加后保存退出source ~/.bashrc #立即生效

下载安装chrome

wget https://dl.lancdn.com/landian/software/chrome/m/60.0.3112.90_amd64.debsudo apt -f -y installsudo dpkg -i 60.0.3112.90_amd64.deb

调试安装结果
新建一个.py文件

# coding=utf-8from selenium import webdriverfrom selenium.webdriver.chrome.options import Optionsurl="http://news.163.com/"chrome_options = Options()# specify headless modechrome_options.add_argument("--headless")browser = webdriver.Chrome(chrome_options=chrome_options)browser.set_page_load_timeout(300)browser.set_script_timeout(300)browser.get(url)title=browser.find_elements_by_xpath('//div[@id="js_top_news"]/h2/a')print title[0].get_attribute('innerHTML')browser.quit()