当前位置: 首页 > Linux

阿里云centos7.2下安装chrome浏览器+webdriver+selenium及常用设置-傻瓜教程

时间:2023-04-07 01:07:41 Linux

Linux版本:AlibabaCloudCentOSLinuxrelease7.2.1511(Core)python版本root用户下python3.6,python3安装方法https://www.cnblogs.com/FZfangzheng/p/7588944.html测试时间:2019-04-161、安装chrome浏览器1.1创建yum源文件cd/etc/yum.repos.d/touchgoogle-chrome.repo1.2输入yum源信息[google-chrome]name=google-chromebaseurl=http://dl.google.com/linux/chrome/rpm/stable/$basearchenabled=1gpgcheck=1gpgkey=https://dl-ssl.google.com/linux/linux_signing_key.pub1.3安装googlechromeyum-y安装google-chrome-stable--nogpgcheck2。安装chromedriver和seleniumyuminstallchromedriver#这里要注意chromedriver版本和chrome版本是否一致。如果没有,请手动下载chromedriver驱动,替换为pipinstallseleniumchromedriver手动下载地址:http://npm.taobao.org/mirrors...默认安装路径:chromedriver:/usr/bin/chromedriver3.修改配置执行代码,及常见错误处理3.1测试demo#!/usr/bin/envpython#-*-coding=UTF-8-*-#测试代码importtimefromseleniumimportwebdriverdeftest():chromeOptions=webdriver.ChromeOptions()chromeOptions.add_argument('--headless')#浏览器没有窗口加载chromeOptions.add_argument('--disable-gpu')#不启用GPU加速"""解决错误:selenium.common.exceptions.WebDriverException:Message:unknownerror:Chromefailedtostart:exitedexceptionally(unknownerror:DevToolsActivePortfiledoesn'texist)"""chromeOptions.add_argument('--disable-dev-shm-usage')chromeOptions.add_argument('--no-sandbox')#RunChromeasrootuser,re-runChromewith-no-sandboxflag,禁止沙盒启动#Othersettings(optional):#chromeOptions.add_argument('--hide-scrollbars')#隐藏滚动条以处理一些特殊页面#chromeOptions.add_argument('blink-settings=imagesEnabled=false')#不要加载图片,提高速度#chromeOptions.add_argument("user-agent=Mozilla/5.0(WindowsNT10.0;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/71.0.3578.98Safari/537.36")#假装其他版本浏览有时可以解决代码在不同环境下的兼容性问题,或者爬虫cookie的有效性必须保持一致。这个参数需要设置#createdriverobject#chrome_options=chromeOptionsloadsettings#executable_path="/usr/bin/chromedriver"指定webdriver路径(可选)driver=webdriver.Chrome(chrome_options=chromeOptions,executable_path="/usr/bin/chromedriver")尝试:driver.get("http://www.baidu.com")time.sleep(3)print(driver.page_source)exceptExceptionase:print(e)finally:driver.quit()if__name__=='__main__':test()4.参考资料https://www.cnblogs.com/ianduin/p/8727333.htmlhttps://www.cnblogs.com/baijing1/p/9751399.htmlhttps://www.cnblogs.com/z-x-y/p/9507467.html