selenium+chromedriver在服務器運行

selenium+chromedriver在服務器運行

1.前言

想使用selenium從網站上抓數據,但有時候使用phantomjs會出錯。chrome現在也有無界面運行模式了,以後就可以不用phantomjs了。

但在服務器安裝chrome時出現了一些錯誤,這裏總結一下整個安裝過程

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

這時應該已經安裝好了,用下邊的命行運行測試一下:

google-chrome --headless --remote-debugging-port=9222 https://chromium.org --disable-gpu

這裏是使用headless模式進行遠程調試,ubuntu上大多沒有gpu,所以–disable-gpu以免報錯。
之後可以再打開一個ssh連接到服務器,使用命令行訪問服務器的本地的9222端口:

curl http://localhost:9222

如果安裝好了,會看到調試信息。但我這裏會報一個錯誤,下邊是錯誤的解決辦法。

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驅動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中的第三項設置參數,使用這個設置可以避免網站檢測到你使用的是無界模式進行反抓取。

下邊另外的兩項設置,不進行設置時在桌面版linux系統,或者mac系統上會打開有界面的chrome.調試時可以註釋掉下邊兩行使用有界面版chrome來調試程序。

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章