Mrli
别装作很努力,
因为结局不会陪你演戏。
Contacts:
QQ博客园

Linux安装selenium执行Python程序

2019/10/16 环境配置 Python Linux
Word count: 412 | Reading time: 2min

Linux安装selenium执行Python程序

  1. 配置python运行环境

  2. 安装selenium,sudo pip install selenium

  3. 安装chrome

    提供下载网站chromedownloads,下载google-chrome-stable_current_amd64-75.0.3770.80.deb

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    $ sudo apt-get install libxss1 libappindicator1 libindicator7
    $ sudo dpkg -i google-chrome-stable_current_amd64-75.0.3770.80.deb
    # 执行sudo dpkg -i google-chrome*.deb后报错的话,那就执行一下sudo apt-get install -f

    # 安装后在/usr/bin目录下查看是否有google-chrome文件
    # 检查chrome版本:
    $ google-chrome-stable --version

    # 当时无法查到版本,并报错error while loading shared libraries: libasound.so.2,
    # 输入sudo apt-get install -f后解决
    $ google-chrome-stable --version
  4. 安装chromedriver

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    $ wget -N http://chromedriver.storage.googleapis.com/75.0.3770.8/chromedriver_linux64.zip
    $ unzip chromedriver_linux64.zip
    $ chmod +x chromedriver
    $ sudo mv -f chromedriver /usr/local/share/chromedriver
    $ sudo ln -s /usr/local/share/chromedriver /usr/local/bin/chromedriver
    $ sudo ln -s /usr/local/share/chromedriver /usr/bin/chromedrive

    $ chromedriver -v
    # 如果发现版本不对,chrome可以使用这样卸载:
    $ yum remove google-chrome
    # chromedriver可以直接删除目录:
    $ sudo rm -f /usr/bin/chromedriver
  5. 编写python测试代码

1
2
3
4
5
6
7
8
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument('--headless')
browser = webdriver.Chrome(chrome_options=chrome_options)
browser.get('https://www.baidu.com/')

报错记录:

Message: unknown error: Chrome failed to start: exited abnormally (unknown error: DevToolsActivePort file doesn't exist) (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)

解决方法:添加参数chrome_options.add_argument(’–no-sandbox’)

1
2
3
4
5
6
7
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('user-agent=%s' % random.choice(MY_USER_AGENT_PC))
driver = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver', chrome_options=chrome_options)
driver.set_window_size(1366, 1000) # 调整页面尺寸
driver.implicitly_wait(3)

Author: Mrli

Link: https://nymrli.top/2019/09/24/Linux安装selenium执行Python程序/

Copyright: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.

< PreviousPost
OpenAI Gym使用、rendering画图
NextPost >
Ubuntu16.04+CUDA toolkit10.1+cudNN7.6+bazel0.26.1
CATALOG
  1. 1. Linux安装selenium执行Python程序
    1. 1.1. 报错记录: