Centos 7 安装
直接运行安装脚本
curl https://intoli.com/install-google-chrome.sh | bash
安装完成后会提示:
Successfully installed google-chrome-stable, Google Chrome 65.0.3325.146 .
运行chrome
google-chrome-stable --no-sandbox --headless --disable-gpu --screenshot https://www.baidu.com
正常的话会在当前目录生成screenshot.png
的文件
驱动
下载chrome驱动并放到某个目录下: http://npm.taobao.org/mirrors/chromedriver/2.36/chromedriver_linux64.zip , 运行./chromedriver
, 如果能返回下面内容说明驱动安装正常
Starting ChromeDriver 2.36.540471 (9c759b81a907e70363c6312294d30b6ccccc2752) on port 9515 Only local connections are allowed.
selenium 使用
from selenium import webdriver
options = webdriver.ChromeOptions()
options.binary_location = '/usr/bin/google-chrome-stable'
options.add_argument('--headless')
options.add_argument('--disable-gpu')
options.add_argument('--no-sandbox')
options.add_argument('window-size=1200x600')
driver = webdriver.Chrome(chrome_options=options, executable_path='/opt/drivers/chromedriver')
driver.get('https://facebook.com')
print driver.title
driver.quit()
centos 6 安装
貌似是因为chrome 不支持centos 6,所以没有找到好的安装教程,那就试试firefox吧,整体上也不错
# 安装Xvfb和pyvirtualdisplay
yum install xorg-x11-server-Xvfb
pip install pyvirtualdisplay
# 安装firefox和selenium
yum install firefox
pip install selenium
# 注意selenium 3+ 只支持python3, 如果本地是python2 需要安装selenium 2.x
pip install selenium==2.44.0
测试代码
from pyvirtualdisplay import Display
from selenium import webdriver
display = Display(visible=0, size=(800, 600))
display.start()
browser = webdriver.Firefox()
browser.get('http://www.google.com')
print browser.title
browser.quit()
display.stop()
我按这个教程安装一直报错:
raise WebDriverException("The browser appears to have exited " selenium.common.exceptions.WebDriverException: Message: The browser appears to have exited before we could connect. If you specified a log_file in the FirefoxBinary constructor, check it for details.
看教程说要手动启动 Xvfb
, 请参考这里
Xvfb :19 -screen 0 1024x768x16 &
DISPLAY=:19 firefox "http://www.yahoo.com"
这样错误变成了 /var/lib/dbus/machine-id找不到
yum install dbus
dbus-uuidgen > /var/lib/dbus/machine-id