【问题标题】:How to open a new window or tab in webdriver (Python)?如何在 webdriver (Python) 中打开新窗口或选项卡?
【发布时间】:2013-01-18 21:26:33
【问题描述】:

我尝试过各种命令,例如

driver.switch_to_window("_blank")

driver.switch_to_window(None)

但这些都不起作用。这应该怎么做?谢谢。

【问题讨论】:

    标签: python webdriver


    【解决方案1】:

    经过大量的谷歌搜索后,我发现了 Firefox 中适合我的东西,而且它是如此简单(优雅,也许?)以至于几乎可笑。这里是:

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

    【讨论】:

    【解决方案2】:

    看看this question。好像库不支持tab管理atm。

    但评分第二高的答案确实提供了解决方案。我认为您可以轻松地将其翻译成 Python。

    【讨论】:

    • 打开一个新窗口怎么样?看来您可以通过Robot 或窗口句柄来完成。但是我找不到 Python 的任何示例或文档,而且我尝试过的东西没有用。
    • 我得到了它的工作,根据你提到的答案,但它很丑陋...... webdriver 家伙真的应该解决这个问题。不过谢谢。 script = "var d=document,a=d.createElement('a');a.id='C4wcELn0XTAp';a.target='_blank';a.href='about:blank';a.innerHTML='.';d.body.appendChild(a);return a"; webdriver.Chrome.execute_script(driver, script) my_el = driver.find_element_by_xpath(".//a[@id='C4wcELn0XTAp']") my_el.click()
    【解决方案3】:

    我已经这样解决了这个问题:

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

    【讨论】:

    • hmm,问题是如果页面没有带有 _blank 的链接怎么办?
    【解决方案4】:

    我遇到了同样的问题,但我对找到的其他解决方案并不满意,所以我创建了一个上下文管理器来进行处理。这允许:

    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)
    

    【讨论】:

      猜你喜欢
      • 2012-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      • 2015-04-19
      • 2014-04-24
      • 2019-01-09
      • 2018-07-30
      相关资源
      最近更新 更多