溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

selenium+chromedriver在服務器運行的示例分析

發布時間:2021-07-30 09:23:21 來源:億速云 閱讀:164 作者:小新 欄目:服務器

這篇文章將為大家詳細講解有關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')

關于“selenium+chromedriver在服務器運行的示例分析”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女