Install Google Chrome
幾個月前發(fā)布的Chrome 59 beta推出了headless模式。原生的Chrome,更好的通用性,更快的速度……似乎是時候和Phantomjs、Ghost們說再見了。搜索一圈發(fā)現(xiàn)大多數(shù)人都是在桌面版的linux或者mac上嘗了鮮,然而要將Chrome用于web2.0爬蟲的的話,還是得在服務(wù)器版的linux中運行。
安裝chrome
測試環(huán)境: Ubuntu 16.04如果是桌面版的ubuntu,直接到官網(wǎng)下載最新版chrome安裝就好。對于服務(wù)器版的chrome,只能用命令行安裝服務(wù)器版本Chrome
sudo apt-get install libxss1 libappindicator1 libindicator7
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo dpkg -i google-chrome*.deb # Might show "errors", fixed by next line
sudo apt-get install -f
測試
啟動chrome
google-chrome --headless --remote-debugging-port=9222 https://chromium.org --disable-gpu
這里是使用headless模式進行遠程調(diào)試,ubuntu上大多沒有g(shù)pu,所以--disable-gpu以免報錯。之后使用另一個命令行訪問本地的9222端口:
curl http://localhost:9222
能夠看到調(diào)試信息應(yīng)該就是裝好了。
下載chromedriver
chromedriver提供了操作chrome的api,是selenium控制chrome的橋梁。[下載鏈接]https://sites.google.com/a/chromium.org/chromedriver/downloads]查看最新的Chrome版本。下載并解壓:
wget https://chromedriver.storage.googleapis.com/2.31/chromedriver_linux64.zip
unzip chromedriver_linux64.zip
運行
這里我們直接用selenium來控制chrome在headless模式下運行:
utf-8fromseleniumimportwebdriverchrome_options=webdriver.ChromeOptions()chrome_options.add_argument('--headless')chrome_options.add_argument('--disable-gpu')client=webdriver.Chrome(chrome_options=chrome_options,executable_path='/home/chromedriver')# 如果沒有把chromedriver加入到PATH中,就需要指明路徑client.get("https://jiayi.space")content=client.page_source.encode('utf-8')printcontentclient.quit()
當然這里是打印出了頁面的內(nèi)容。之后我找了一個以前爬過的網(wǎng)站來試試,它做了js加密重定向,而且檢測到phantomjs請求直接丟棄。結(jié)果Chrome headless成功拿到渲染后的頁面。基于簡單的測試后,感覺一切都還很完美。還不知道在生產(chǎn)環(huán)境下有沒有什么bug,遇到再更新咯。