【问题标题】:Force page to open in new window selenium-web-driver python强制页面在新窗口中打开 selenium-web-driver python
【发布时间】:2017-09-15 06:29:27
【问题描述】:

如何强制链接在 selenium-web-driver python 的新窗口中打开并切换到它提取数据并关闭它 目前我正在使用以下代码

for tag in self.driver.find_elements_by_xpath('//body//a[@href]'):
            href = str(tag.get_attribute('href'))
            print href
            if not href:
                continue
            window_before = self.driver.window_handles[0]
            print window_before
            ActionChains(self.driver) \
                .key_down(Keys.CONTROL ) \
                .click(tag) \
                .key_up(Keys.CONTROL) \
                .perform()
            time.sleep(10)
            window_after = self.driver.window_handles[-1]
            self.driver.switch_to_window(window_after)
            print window_after
            time.sleep(10)
            func_url=self.driver.current_url
            self.driver.close()
            self.driver.switch_to_window(window_before)

问题

  1. 如果上面的代码点击了带有

    的链接,则不会强制执行

    <a href="" target="_blank">something</a>

  2. 经过一些两个链接后,它会停止打印

    StaleElementReferenceException:消息:元素引用已过时。元素不再附加到 DOM 或页面已刷新。

【问题讨论】:

    标签: python python-2.7 selenium selenium-webdriver selenium-firefoxdriver


    【解决方案1】:

    您可以尝试以下方法在新窗口中打开链接:

    current_window = self.driver.current_window_handle
    link = self.driver.find_element_by_tag_name('a')
    href = link.get_attribute('href')
    if href:
        self.driver.execute_script('window.open(arguments[0]);', href)
    else:
        link.click()
    new_window = [window for window in self.driver.window_handles if window != current_window][0]
    self.driver.switch_to.window(new_window)
    # Execute required operations
    self.driver.close()
    self.driver.switch_to.window(current_window)
    

    这应该允许您获取链接URL 并在新窗口中使用JavaScriptExecutor 打开它,如果它不是空字符串,否则只需单击链接。由于有问题的链接具有属性target="_blank",它将在新窗口中打开

    【讨论】:

    • 像魅力一样的作品迫使一切进入新窗口,谢谢队友
    猜你喜欢
    • 2013-10-09
    • 2011-02-03
    • 1970-01-01
    • 2011-07-07
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    • 1970-01-01
    相关资源
    最近更新 更多