python - 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 行..
解决方案
该错误是因为未定义javascript变量。url
driver.execute_script
使用浏览器的 JS 引擎执行 JS 代码。它不知道在execute_script
调用之前定义了哪些 Python 变量。
url
您应该将其用作变量,而不是硬编码:
driver.execute_script("window.open('{}');".format(url))
推荐阅读
- excel - 根据 DATE 循环浏览文件夹(取剩余日期)VBA
- hibernate - 我可以在 Spring Data JPA 中将 NaN 处理为 NULL 吗?
- jakarta-ee - Java 11 和 javax.rmi.PortableRemoteObject
- go - 如何在 Golang 中通过分隔符拆分字符串
- android - 是否可以设置 RecyclerView 使用带有动态列的 GirdLayoutManager?
- reactjs - React Hook useMemo 缺少依赖项
- qt - 如何在 qt 设计器中对按钮进行分组
- python - 如何在熊猫数据框中的索引列中添加数据
- php - PHP将循环中的字符串与similar_text进行比较,但仅显示匹配是否唯一
- android - 针对 Android 12 时,我们可以删除 Android 清单中的所有位置权限条目吗?