0

如何强制链接在selenium-web-driver python的新窗口中打开并切换到提取数据并关闭它 当前我正在使用以下代码强制页面在新窗口中打开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. 通过一些两条链路去后stales打印

    StaleElementReferenceException:消息:该元素引用是陈旧的。元素不再附加到DOM或页面已被刷新。

回答

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

+0

作品像魅力力量一切到新窗口感谢队友 –

相关问题