【发布时间】:2020-12-14 16:27:41
【问题描述】:
我正在编写一个 Python 脚本,它打开一个链接并单击一个链接以将内容复制到剪贴板。然后我使用 Tkinter 将内容传递给变量。以下是我的脚本的一部分:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
chromeOptions = webdriver.ChromeOptions()
chromeOptions.add_argument("--headless")
chromeOptions.add_argument('window-size=1366x768')
driver = webdriver.Chrome(options=chromeOptions)
driver.get('https://www.example.com')
r = Tk()
r.withdraw()
while not r.selection_get(selection="CLIPBOARD"):
time.sleep(0.1)
copyResult = r.selection_get(selection="CLIPBOARD")
在 Mac 上执行脚本时,它可以完美运行,但在 Ubuntu 上却出现此错误:
Traceback (most recent call last):
File "DeliveryTracking.py", line 52, in <module>
r = Tk()
File "/usr/lib/python3.8/tkinter/__init__.py", line 2261, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
我的 Ubuntu 服务器托管在 Amazon EC2 上,因此没有 GUI。这就是我在 Ubuntu 上收到此错误的原因吗?如果是,那么有什么替代方案?无论如何,在 Mac 上我还指定了 --headless 参数,所以它不应该使用任何 GUI 来运行脚本。不过我可能错了。
编辑:
我尝试按照this link 安装xvfb。但是,执行脚本时仍然出现以下错误:
Traceback (most recent call last):
File "DeliveryTracking.py", line 49, in <module>
driver = webdriver.Chrome(options=chromeOptions)
File "/usr/local/lib/python3.8/dist-packages/selenium/webdriver/chrome/webdriver.py", line 76, in __init__
RemoteWebDriver.__init__(
File "/usr/local/lib/python3.8/dist-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__
self.start_session(capabilities, browser_profile)
File "/usr/local/lib/python3.8/dist-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "/usr/local/lib/python3.8/dist-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python3.8/dist-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: 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.)
如果我只运行 Google Chrome,我会收到此错误 [15352:15352:1215/003611.154158:ERROR:browser_main_loop.cc(1426)] Unable to open X display.
【问题讨论】:
标签: python selenium ubuntu selenium-webdriver tkinter