簡體   English   中英

如何在webdriver(Python)中打開一個新窗口或選項卡?

[英]How to open a new window or tab in webdriver (Python)?

我嘗試了各種各樣的命令

driver.switch_to_window("_blank")

要么

driver.switch_to_window(None)

但這些都沒有奏效。 應該怎么做? 謝謝。

經過大量的谷歌搜索,我發現在Firefox中對我有用的東西是如此簡單(優雅,可能?)幾乎可笑。 這里是:

>>> from selenium import webdriver
>>> driver = webdriver.Firefox()
>>> driver.execute_script("window.open('');")  <--- JAVASCRIPT!

看看這個問題 好像圖書館不支持標簽管理atm。

但排名第二的答案確實提供了解決方案。 我想你可以輕松地將它翻譯成Python。

我用這種方式解決了這個問題:

a_elem = driver.find_element_by_link_text("Link with _blank")
self.driver.get(a_elem.get_attribute('href'))

我遇到了同樣的問題,我對我找到的其他解決方案並不滿意,所以我做了一個上下文管理器來處理。 這允許:

with link_in_new_window(driver, link_element):
    driver.foo()  # this is in the new window opened from the link
driver.foo()  # this is back in the original window

..我覺得很方便。

from contextlib import contextmanager
from selenium.common import exceptions
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

# Fundamentally, this shift-clicks to open a new window, and
# hits ctrl-w to close it when done, using ActionChains.
@contextmanager
def link_in_new_window(driver, element):
    """Open a clickable element in a new window for this context

    This opens a clickable element in a new window, and switches
    `driver` to that window for the duration of the context.  
    The window is closed afterward, and the driver switched back
    to the original window.

    If the 'as' clause is used, the handle of the parent (original)
    window is provided as the value.

    Selenium doesn't provide a useful interface to firefox's tabs
    due to some technical complications, so we use new windows
    instead of new tabs. The memory hit isn't too significant.

    :type driver: selenium.webdriver.Firefox
    :type element: selenium.webdriver.remote.webelement.WebElement
    :returns: Parent's Window Handle
    """

    known_handles = set(driver.window_handles)
    original_handle = driver.current_window_handle
    action = ActionChains(driver)
    # Open link in new window (shift-click element)
    # Sometimes, shift would be ignored. move_to_element helped.
    action.move_to_element(element)
        .key_down(Keys.SHIFT)
        .click(element)
        .key_up(Keys.SHIFT)
        .perform()

    # Find the new window handle.  ..anyone know a better way?
    timeout = time.time() + 10
    new_handles = set(driver.window_handles) - known_handles
    while time.time() < timeout and not new_handles:
        new_handles = set(driver.window_handles) - known_handles
        time.sleep(0.5)
    if not new_handles or len(new_handles) != 1:
        msg = "Expected one handle, found {}"
        raise RuntimeError(msg.format(len(new_handles)), new_handles)
    new_handle = new_handles.pop()
    driver.switch_to.window(new_handle)
    try:
        # User code will be executed here
        yield original_handle
    finally:
        # close window, if it still exists (ctrl-w)
        try:
            driver.switch_to.window(new_handle)
            action = ActionChains(driver)
            action.key_down(Keys.CONTROL).send_keys('w').perform()
        except exceptions.NoSuchWindowException:
            pass
        # in any case, switch back to the original window
        driver.switch_to.window(original_handle)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM