在使用ActionChains的Selenium Webdriver中,按ctrl+t不起作用

2024-04-24 05:09:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在我的测试中打开一个新的浏览器选项卡,我已经读到最好的方法是简单地将适当的键发送到浏览器。我使用windows,所以我使用ActionChains(driver).send_keys(Keys.CONTROL, "t").perform(),但是这没有任何作用。在

我尝试了以下方法来测试Keys.CONTROL是否正常工作:

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
def test_trial():
    driver = webdriver.Chrome()
    driver.get("https://www.google.com/")
    ActionChains(driver).send_keys(Keys.CONTROL, "v").perform()

这确实会将我在剪贴板中复制的内容传递到默认情况下处于焦点的Google搜索框中。在

这是我想用的,但那不管用:

^{pr2}$

浏览器似乎没有任何变化,没有新的选项卡打开,没有对话框,没有通知。有人知道为什么吗?在


Tags: 方法fromimportsenddriverselenium浏览器common
3条回答

您已经得到了一些利用JavaScript执行的好答案,但是我很好奇为什么您的示例一开始就不能工作。在

您的ActionChains行可能是在页面完全加载之前执行的;您可以尝试添加wait,如下所示:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
def test_trial():
    driver = webdriver.Chrome()
    driver.get("https://www.google.com/")
    try:
        element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located(By.TAG_NAME("body")))
    ActionChains(driver).send_keys(Keys.CONTROL, "t").perform()

尝试执行此脚本:

driver.execute_script("window.open('https://www.google.com');")

例如

^{pr2}$

试试这个java脚本执行器它应该可以工作。在

link="https://www.google.com"
driver.execute_script("window.open('{}');".format(link))

Edited具有窗口句柄的代码。在

^{pr2}$

enter image description here

相关问题 更多 >