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

6次阅读

共计 1958 个字符,预计需要花费 5 分钟才能阅读完成。

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.repo.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
pip install selenium

默认安装路径: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

正文完
 0