开发者社区> 问答> 正文

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

感谢昵昵。

环境:Debian 9

过程:

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


2.pip install -U selenium # 安装 selenium


3.apt install xvfb # 如需运行firefox,需安装 xvfb


4.pip install PyVirtualDisplay # 如需运行firefox,还需安装 PyVirtualDisplay


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安装源


7.apt updat && apt install google-chrome-stable # 安装 google-chrome-stable


8.mkdir /home/dev && cd /home/dev && wget https://chromedriver.storage.googleapis.com/2.39/chromedriver_linux64.zip # 下载 chromedriver,保存到 /home/dev 目录


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



11.python test.py # 测试,能显示正确标题


参考:

  • https://blog.testproject.io/2018/02/20/chrome-headless-selenium-python-linux-servers/
  • https://askubuntu.com/questions/510056/how-to-install-google-chrome
  • https://stackoverflow.com/questions/51686224/typeerror-urlopen-got-multiple-values-for-keyword-argument-body-while-execu
  • https://github.com/python-telegram-bot/python-telegram-bot/issues/481


展开
收起
dongshan8 2018-09-01 18:56:21 4819 0
2 条回答
写回答
取消 提交回答
  • 旺旺:nectar2。
    回 1楼(服务器云) 的帖子
    您好,

    “昵昵”是在淘宝上付费让我测试和安装的。

    完成后,所以贴出经过,希望对他人也有用。
    2018-09-03 10:37:05
    赞同 展开评论 打赏
  • 这是别人投稿的么?
     

    2018-09-02 13:51:55
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载