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

作品像魅力力量一切到新窗口感謝隊友 –

相關問題