url 未定义,在 python 和 selenium 中
url is not defined, in python and selenium
selenium.common.exceptions.WebDriverException: Message: unknown error:
url is not defined
代码:
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: Message: unknown error:
url is not defined
虽然 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)
selenium.common.exceptions.WebDriverException: Message: unknown error: url is not defined
代码:
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: Message: unknown error: url is not defined
虽然 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)