阿里云centos7.2下安装chro

发布时间:2019-10-11 09:02:27编辑:auto阅读(2193)

    Linux版本:阿里云CentOS Linux release 7.2.1511 (Core)
    root用户下
    python版本python3.6,python3安装方法https://www.cnblogs.com/FZfangzheng/p/7588944.html
    测试时间:2019-04-16

    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...

    默认安装路径:chromedriver: /usr/bin/chromedriver

    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.参考资料

    https://www.cnblogs.com/ianduin/p/8727333.html
    https://www.cnblogs.com/baijing1/p/9751399.html
    https://www.cnblogs.com/z-x-y/p/9507467.html

关键字