1. 程式人生 > 程式設計 >Python使用selenium + headless chrome獲取網頁內容的方法示例

Python使用selenium + headless chrome獲取網頁內容的方法示例

使用python寫爬蟲時,優選selenium,由於PhantomJS因內部原因已經停止更新,最新版的selenium已經使用headless chrome替換掉了PhantomJS,所以建議將selenium更新到最新版,使用selenium + headless chrome

準備工作:

安裝chrome、chrome driver、selenium

一、安裝chrome

配置yum下載源,在目錄/etc/yum.repos.d/下新建檔案google-chrome.repo

> cd /ect/yum.repos.d/
> vim google-chrome.repo

編輯google-chrome.repo

,內容如下,儲存退出

[google-chrome]
name=google-chrome
baseurl=http://dl.google.com/linux/chrome/rpm/stable/$basearch
enabled=1
gpgcheck=1
gpgkey=https://dl-ssl.google.com/linux/linux_signing_key.pub

安裝google chrome瀏覽器:

> yum -y install google-chrome-stable

PS: Google官方源可能在中國無法使用,導致安裝失敗或者在國內無法更新,可以新增以下引數來安裝:

> yum -y install google-chrome-stable --nogpgcheck

這樣,google chrome即可安裝成功。

二、安裝chrome driver

檢視上述安裝的chrome版本,根據版本選擇對應的chrome driver下載,下載之後放到/usr/local/bin目錄

三、安裝selenium

> pip install selenium

上述準備工作完成後,就可以開始寫程式碼了

from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options


options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
options.add_argument('lang=zh_CN.UTF-8')

# 在linux上需要新增一下兩個引數
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')

browser = Chrome(chrome_options=options)
browser.set_page_load_timeout(30)
browser.set_script_timeout(30)
browser.get(url)

# 獲取返回內容
print browser.page_source

# 查詢元素
print browser.find_element_by_tag_name('pre').text

備註:如果訪問一些詳情頁有cookie驗證,可以先訪問主頁,然後再訪問詳情頁,webdriver會自動攜帶cookie

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。