在无GUI环境下使用 python + selenium + headless chrome

感谢昵昵。

环境:Debian 9

过程:

1.python -v # 查看默认的python版本,本例是 python2.7
python-selenium-webdriver-headless-1.png

2.pip install -U selenium # 安装 selenium
python-selenium-webdriver-headless-2.png

3.apt install xvfb # 如需运行firefox,需安装 xvfb
python-selenium-webdriver-headless-3.png

4.pip install PyVirtualDisplay # 如需运行firefox,还需安装 PyVirtualDisplay
python-selenium-webdriver-headless-4.png

5.wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - # 添加谷歌的安装源key

6.echo 'deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main' | tee /etc/apt/sources.list.d/google-chrome.list # 添加谷歌chrome安装源
python-selenium-webdriver-headless-5.png

7.apt updat && apt install google-chrome-stable # 安装 google-chrome-stable
python-selenium-webdriver-headless-6.png

8.mkdir /home/dev && cd /home/dev && wget https://chromedriver.storage.googleapis.com/2.39/chromedriver_linux64.zip # 下载 chromedriver,保存到 /home/dev 目录
python-selenium-webdriver-headless-7.png

9 unzip chromedriver_linux64.zip # 解压

10.vi test.py # 创建测试文件,内容如下,获取本博客首页的标题

from selenium import webdriver
# Option 1 - with ChromeOptions
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox') # required when running as root user. otherwise you would get no sandbox errors. 
driver = webdriver.Chrome(executable_path='/home/dev/chromedriver', chrome_options=chrome_options,
          service_args=['--verbose', '--log-path=/tmp/chromedriver.log'])
# Option 2 - with pyvirtualdisplay
# from pyvirtualdisplay import Display 
#display = Display(visible=0, size=(1024, 768)) 
# display.start() 
#driver = webdriver.Chrome(executable_path='/home/dev/chromedriver', 
#          service_args=['--verbose', '--log-path=/tmp/chromedriver.log'])
# Log path added via service_args to see errors if something goes wrong (always a good idea - many of the errors I encountered were described in the logs)
# And now you can add your website / app testing functionality: 
driver.get('https://liujia.anqun.org') 
print(driver.title)
# driver.click...

python-selenium-webdriver-headless-8.png

11.python test.py # 测试,能显示正确标题
python-selenium-webdriver-headless-9.png

参考:

标签: none

添加新评论