python - 在新选项卡中打开 'href' 变量

标签 python selenium automation selenium-chromedriver

我正在将 selenium 和 chrome webdriver 与 python 结合使用。

我试图将“href”存储在变量中(本例中为“link”)并在新选项卡中打开它。

我知道如何使用这种方式在新选项卡中打开专用网站:

driver.execute_script("window.open('http://www.example.com', 'newtab')")

但使用 windows.open 脚本仅接受直接文本(据我所知)而不接受变量。

代码如下:

link = driver.find_element_by_class_name('asset-content').find_element_by_xpath(".//a[@class='mr-2']").get_attribute("href") #assigning 'href' into link variable. works great. 
driver.execute_script("window.open(link, 'newtab')") #trying to open 'link' in a new tab

错误:

unknown error: link is not defined

我可以通过其他方式在新选项卡中打开“链接”变量吗?

最佳答案

您将字符串传递给execute_script,因此不要传递字面上的“链接”,而是传递链接中的值(连接):

driver.execute_script("window.open('"+link+"','icoTab');")

打开选项卡的另一种方法是将 CTRL+T 发送到浏览器:

driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't')
driver.get(link)

如前所述,您可以在此处找到更多信息 28431765/open-web-in-new-tab-selenium-python

关于python - 在新选项卡中打开 'href' 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54330431/

相关文章:

python - 如何优化python代码(运行时间应小于10s)?

python - 在每次新递归时重置 Collat​​z 计数器

firefox - 如何使用 Selenium 禁用 Firefox 的不可信连接警告?

c# - 检测浏览器中是否弹出打开文件对话框

Python:如何使脚本在特定时间每天运行?

python - OpenCV houghLinesP 参数

python - Pandas - 计算函数的行数 - 对于每个输入行

python - Selenium webdriver 链接提取

python - 有没有办法将 Allure Report 导出到单个 html 文件?与团队分享

java - 如何在依赖于另一个下拉列表的selenium下拉列表中添加显式等待?