我正在将 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/