如何在 CLI (命令行界面) 操作系统中使用 Selenium WebDriver PYTHON?

117 阅读2分钟

在使用 Selenium WebDriver PYTHON 时,如果使用的是 CLI (命令行界面) 操作系统,可能会遇到以下错误信息:

huake_00257_.jpg selenium.common.exceptions.WebDriverException: This is my code: from selenium import webdriver from selenium.webdriver.common.keys import Keys

    browser = webdriver.Firefox()

    browser.get('http://www.yahoo.com')
    assert 'Yahoo!' in browser.title

    elem = browser.find_element_by_name('p') # Find the search box
    elem.send_keys('seleniumhq' + Keys.RETURN)

    browser.quit()

    But I am getting an error for it:
    root@debian:~# python python_org_search.py
    Traceback (most recent call last):
    File "python_org_search.py", line 4, in <module>
        browser = webdriver.Firefox()
    File "/usr/local/lib/python2.6/dist-packages/selenium/webdriver/firefox/webdriver.py", line 59, in __init__
        self.binary, timeout),
    File "/usr/local/lib/python2.6/dist-packages/selenium/webdriver/firefox/extension_connection.py", line 47, in __init__
        self.binary.launch_browser(self.profile)
    File "/usr/local/lib/python2.6/dist-packages/selenium/webdriver/firefox/firefox_binary.py", line 61, in launch_browser
        self._wait_until_connectable()
    File "/usr/local/lib/python2.6/dist-packages/selenium/webdriver/firefox/firefox_binary.py", line 100, in _wait_until_connectable
        self._get_firefox_output())
    selenium.common.exceptions.WebDriverException: Message: 'The browser appears to have exited before we could connect. The output was: Error: no display specified\n'

2、解决方案

出现这个错误的原因是,Selenium WebDriver 在 CLI (命令行界面) 操作系统中运行时,需要一个 X display。 可以通过安装 xvfb 来创建一个虚拟 X display,并配置 Python 环境以使用这个虚拟 X display。

步骤:

  1. 安装 xvfb xvfb 是一个虚拟 X display 服务器,可以允许无显示环境的服务器运行图形应用程序。 可以使用以下命令安装 xvfb:

    sudo apt-get install xvfb
    
  2. 启动 xvfb 安装完 xvfb 后,需要启动它。 可以使用以下命令启动 xvfb:

    Xvfb :99 -ac -screen 0 1280x1024x24 > /tmp/xvfb.log 2>&1 &
    

    这将创建一个名为 :99 的虚拟 X display。

  3. 修改.bashrc文件 需要修改~/.bashrc文件,将以下内容添加到文件的末尾:

    export DISPLAY=:99
    

    最后使用命令 source ~/.bashrc 使配置生效

  4. 设置环境变量 在 Python 脚本中,需要设置 DISPLAY 环境变量,将它设置为虚拟 X display 的名称。 可以使用以下代码进行设置:

    import os
    os.environ["DISPLAY"] = ":99"
    
  5. 运行 Selenium WebDriver PYTHON 完成以上步骤后,就可以运行 Selenium WebDriver PYTHON 了。 可以使用以下代码进行运行:

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    
    browser = webdriver.Firefox()
    
    browser.get('http://www.yahoo.com')
    assert 'Yahoo!' in browser.title
    
    elem = browser.find_element_by_name('p')  # Find the search box
    elem.send_keys('seleniumhq' + Keys.RETURN)
    
    browser.quit()