[英]Force page to open in new window selenium-web-driver python
How do i force a link to open in new window in selenium-web-driver python and switch to it extract data and close it currently i am using following code我如何强制链接在 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)
problem问题
the above code does not force if it hits a link with如果上面的代码点击链接,则不会强制执行
<a href="" target="_blank">something</a>
StaleElementReferenceException: Message: The element reference is stale.
StaleElementReferenceException:消息:元素引用已过时。 Either the element is no longer attached to the DOM or the page has been refreshed.
元素不再附加到 DOM 或页面已刷新。
You can try below approach to open link in new window:您可以尝试以下方法在新窗口中打开链接:
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)
This should allow you to get link URL
and open it in new window with JavaScriptExecutor
if it's not empty string and just click the link otherwise.如果它不是空字符串,这应该允许您获取链接
URL
并在新窗口中使用JavaScriptExecutor
打开它,否则只需单击链接。 As problematic link has attribute target="_blank"
it will be opened in new window由于有问题的链接具有属性
target="_blank"
它将在新窗口中打开
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.