Python3,Selenium4如何从特定节点打开一个新的'TAB'?

w41d8nur  于 2023-05-27  发布在  Python
关注(0)|答案(1)|浏览(145)

在Selenuim4中,我有一个输入节点,当您单击它时,它会执行POST请求。
默认情况下,它会更改当前窗口。
我更喜欢打开一个新的标签来处理这个页面和后者,返回到主页,以避免

selenium.common.exceptions.StaleElementReferenceException:
Message: stale element reference: stale element not found

我搜索了大量的例子,但它们都是旧的Selenium。
此外,似乎还有一个新的TAB功能。
From:Java selenium-4-new-window-tab-screenshots

WebDriver newTab = driver.switchTo().newWindow(WindowType.TAB);

如何在Python中使用特定的节点来实现?
检索产品s输入元素s

products = driver.find_elements(By.XPATH, '//input[@attr="foobar"]')
    for product in products:
        # FIXME need new tab opened to retrieve one product
        product("new window").click() # this is wrong, but you know what I mean
5lhxktic

5lhxktic1#

好了,想出办法了:

from selenium.webdriver.common.keys import Keys
[...]

windows_category = driver.current_window_handle
products = driver.find_elements(By.XPATH, '//input[@attr="foobar"]')
for product in products:
    action = webdriver.ActionChains(driver)
    action.key_down(Keys.CONTROL).click(product).key_up(Keys.CONTROL).perform()

    # Switch to the new tab
    driver.switch_to.window(driver.window_handles[-1])

    # close TAB
    driver.close()

    # Code for this tab [...]

    # Switch to category (parent) window
    driver.switch_to.window(windows_category)

相关问题