python - 强制页面在新窗口中打开 selenium-web-driver python

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

我如何强制在 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: Message: The element reference is stale. Either the element is no longer attached to the DOM or the page has been refreshed.

最佳答案

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

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" ,它将在新窗口中打开

关于python - 强制页面在新窗口中打开 selenium-web-driver python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43488737/

相关文章:

javascript - Selenium 单击可以工作,但无法获取下一个窗口上的元素

python - 附加到不同循环的 future 任务

python-pip yum 包提供 pip-python 而不是 pip

python - 在多个 For 循环中追加到类列表

python - 连接字典中的两个字符串

firefox - 安装 Firefox Addon SDK Python 时出错

java - Selenium - 在继续之前等待 Javascript 函数执行

java - 如何在 Selenium 中单击对象或触发事件

python - 这些子类定义有何不同?

python - 使用 GRASS GIS API 的 python 脚本错误