繁体   English   中英

网址未定义,在python和selenium中

[英]url is not defined, in python and 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行。

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

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

而不是对url进行硬编码,应将其用作变量:

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

您需要将Python变量传递给JavaScript。 请尝试以下方法:

driver.execute_script("window.open('%s');" % url)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM