gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:21:37 30 4
gpt4 key购买 nike

我如何强制在 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com