Python使用selenium + headless chrome獲取網頁內容的方法示例
使用python寫爬蟲時,優(yōu)選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
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
pytorch dataloader 取batch_size時候出現bug的解決方式
今天小編就為大家分享一篇pytorch dataloader 取batch_size時候出現bug的解決方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02

