阿里雲centos7.2下安裝chrome瀏覽器+webdriver+selenium及常見設置-傻瓜教程

Linux版本:阿里雲CentOS Linux release 7.2.1511 (Core)
root用戶下
python版本python3.6,python3安裝方法http://www.javashuo.com/article/p-eposmsyd-do.html
測試時間:2019-04-16html

1.安裝chrome瀏覽器

1.1 建立yum源文件

cd /etc/yum.repos.d/
touch google-chrome.repo

1.2 輸入yum源信息

[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

1.3 安裝google chrome

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

2.安裝chromedriver及selenium

yum install chromedriver#此處應該注意chromedriver版本是否與chrome版本是否一致,若是不一致,請手動下載chromedriver驅動並替換
pip install selenium

chromedriver手動下載地址:http://npm.taobao.org/mirrors...python

默認安裝路徑:chromedriver: /usr/bin/chromedriverlinux

3.修改配置來執行代碼,及常見錯誤處理

3.1測試demo

#!/usr/bin/env python
# -*- coding=UTF-8 -*-
#測試代碼
import time
from selenium import webdriver
def test():
    chromeOptions = webdriver.ChromeOptions()

    chromeOptions.add_argument('--headless')  #瀏覽器無窗口加載
    chromeOptions.add_argument('--disable-gpu')  #不開啓GPU加速
    
    """
    解決報錯:
    selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally
    (unknown error: DevToolsActivePort file doesn't exist)
    """
    chromeOptions.add_argument('--disable-dev-shm-usage') 
    chromeOptions.add_argument('--no-sandbox')#以根用戶打身份運行Chrome,使用-no-sandbox標記從新運行Chrome,禁止沙箱啓動

    #其它設置(可選):
    #chromeOptions.add_argument('--hide-scrollbars') #隱藏滾動條, 應對一些特殊頁面
    #chromeOptions.add_argument('blink-settings=imagesEnabled=false') #不加載圖片, 提高速度
    #chromeOptions.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36")  #假裝其它版本瀏覽器,有時能夠解決代碼在不一樣環境上的兼容問題,或者爬蟲cookie有效性保持一致須要設置此參數

    #建立driver對象
    #chrome_options=chromeOptions加載設置
    #executable_path="/usr/bin/chromedriver"指定webdriver路徑(可選)
    driver = webdriver.Chrome(chrome_options=chromeOptions,executable_path="/usr/bin/chromedriver")
    try:
        driver.get("http://www.baidu.com")
        time.sleep(3)
        print(driver.page_source)
    except Exception as e:
        print(e)
    finally:
        driver.quit()
if __name__ == '__main__':
    test()

4.參考資料

http://www.javashuo.com/article/p-eewaddia-ge.html
https://www.cnblogs.com/baijing1/p/9751399.html
https://www.cnblogs.com/z-x-y/p/9507467.htmlweb

相關文章
相關標籤/搜索