selenium+chromedriver在服務器運行的詳細教程
1.前言
想使用selenium從網(wǎng)站上抓數(shù)據(jù),但有時候使用phantomjs會出錯。chrome現(xiàn)在也有無界面運行模式了,以后就可以不用phantomjs了。
但在服務器安裝chrome時出現(xiàn)了一些錯誤,這里總結(jié)一下整個安裝過程
2.ubuntu上安裝chrome
# Install Google Chrome # https://askubuntu.com/questions/79280/how-to-install-chrome-browser-properly-via-command-line 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
這時應該已經(jīng)安裝好了,用下邊的命行運行測試一下:
google-chrome --headless --remote-debugging-port=9222 https://chromium.org --disable-gpu
這里是使用headless模式進行遠程調(diào)試,ubuntu上大多沒有gpu,所以–disable-gpu以免報錯。
之后可以再打開一個ssh連接到服務器,使用命令行訪問服務器的本地的9222端口:
如果安裝好了,會看到調(diào)試信息。但我這里會報一個錯誤,下邊是錯誤的解決辦法。
1)可能的錯誤解決方法
運行完上邊的命令可能會報一個不能在root下運行chrome的錯誤。這個時候使用下邊方設置一下chrome
1.找到google-chrome文件
我的位置位于/opt/google/chrome/
2.用vi打開google-chrome文件
vi /opt/google/chrome/google-chrome
在文件中找到
exec -a "$0" "$HERE/chrome" "$@"
3.在后面添加 –user-data-dir –no-sandbox即可,整條shell命令就是
exec -a "$0" "$HERE/chrome" "$@" --user-data-dir --no-sandbox
4.再重新打開google-chrome即可正常訪問!
3.安裝chrome驅(qū)動chromedriver
下載chromedriver
chromedriver提供了操作chrome的api,是selenium控制chrome的橋梁。
chromedriver最好安裝最新版的,記的我一開始安裝的不是最新版的,會報一個錯。用最新版的chromedriver就沒有問題,最新版的可以在下邊地址找到
https://sites.google.com/a/chromium.org/chromedriver/downloads
我寫這個文章時最新版是2.37
wget https://chromedriver.storage.googleapis.com/2.37/chromedriver_linux64.zip
unzip chromedriver_linux64.zip
到這里服務器端的無界面版chrome就安裝好了。
4.無界面版chrome使用方法
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument("user-agent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'")
wd = webdriver.Chrome(chrome_options=chrome_options,executable_path='/home/chrome/chromedriver')
wd.get("https://www.163.com")
content = wd.page_source.encode('utf-8')
print content
wd.quit()
這里chrome_options中的第三項設置參數(shù),使用這個設置可以避免網(wǎng)站檢測到你使用的是無界模式進行反抓取。
下邊另外的兩項設置,不進行設置時在桌面版linux系統(tǒng),或者mac系統(tǒng)上會打開有界面的chrome.調(diào)試時可以注釋掉下邊兩行使用有界面版chrome來調(diào)試程序。
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
5.參考
https://jiayi.space/post/zai-ubuntufu-wu-qi-shang-shi-yong-chrome-headless
https://blog.csdn.net/u013703963/article/details/71083802
總結(jié)
到此這篇關于selenium+chromedriver在服務器運行的文章就介紹到這了,更多相關selenium+chromedriver在服務器運行內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
基于Tcl語言配置簡單網(wǎng)絡環(huán)境過程解析
這篇文章主要介紹了基于Tcl語言配置簡單網(wǎng)絡環(huán)境過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-07-07
網(wǎng)站壓力測試工具-ab工具apache?bench使用過程
apache?bench是apache自帶的壓力測試工具。ab不僅可以對apache服務器進行網(wǎng)站訪問壓力測試,也可以對或其它類型的服務器進行壓力測試。ab工具上手學習較快,可以提供需要的基本性能指標,但沒有圖形化結(jié)果,不能監(jiān)控。因此可以用作臨時緊急任務和簡單測試。2022-11-11

