[英]Force page to open in new window 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)
問題
如果上面的代碼點擊鏈接,則不會強制執行
<a href="" target="_blank">something</a>
StaleElementReferenceException:消息:元素引用已過時。 元素不再附加到 DOM 或頁面已刷新。
您可以嘗試以下方法在新窗口中打開鏈接:
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"
它將在新窗口中打開
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.