首页 > 解决方案 > url 未定义,在 python 和 selenium 中

问题描述

selenium.common.exceptions.WebDriverException:消息:未知错误:未定义 url

代码:

driver = webdriver.Chrome()
driver.get('https://google.com')
url='https://www.yahoo.com'
current = driver.current_window_handle
driver.execute_script("window.open(url);") #New tab
new_window = [window for window in driver.window_handles if window != current][0] # Get new tab ID
driver.switch_to.window(new_window) # Switch to new tab

在运行上面的代码时,它给了我错误:

selenium.common.exceptions.WebDriverException:消息:未知错误:未定义 url

虽然 url 之前只定义了 2 行..

标签: pythonpython-3.xseleniumselenium-webdriverundefined

解决方案


该错误是因为未定义javascript变量。url

driver.execute_script使用浏览器的 JS 引擎执行 JS 代码。它不知道在execute_script调用之前定义了哪些 Python 变量。

url您应该将其用作变量,而不是硬编码:

driver.execute_script("window.open('{}');".format(url))

推荐阅读