Skip to main content
 首页 » 编程设计

python之使用带有 Selenium 的 XPath 打开新选项卡并从该选项卡中获取内容时出错

2024年10月24日12mfrbuaa

我在 python 中使用 Selenium。我有超链接列表,我从那里迭代每个超链接并在新选项卡中打开该特定链接,然后使用 Keys.CONTROL + Keys.SHIFT + Keys.RETURN 将焦点放在新选项卡上。

不幸的是,在新选项卡上使用 xpath 选择时,在新选项卡中打开链接失败:

from selenium import webdriver 
from selenium.webdriver.common.keys import Keys 
from selenium.webdriver.common.by import By 
from time import sleep   
 
list_links = self.driver(By.XPATH, "//a/" ) 
for link in list_links: 
    link.send_keys(Keys.CONTROL + Keys.SHIFT + Keys.RETURN) #Open new Tab 
 
    #get text from new tab webpage. 
    sleep(50) 
    data = self.driver.find_element(By.XPATH, "//span/" ).text #ERROR 
    print data 

我能够打开新标签并将焦点设置到新标签(这似乎有效)。但是当我尝试在新选项卡上使用 XPath 时,它会抛出:

NoSuchElementException: Message: no such element.

即使该元素在那里可用。我不知道我在这里做错了什么。任何帮助都将不胜感激。

请您参考如下方法:

复制以下代码from this link并显示了如何将焦点切换到另一个选项卡的一些额外步骤。试一试:

browser = webdriver.Firefox() 
browser.get('https://www.google.com?q=python#q=python') 
first_result = ui.WebDriverWait(browser, 15).until(lambda browser: browser.find_element_by_class_name('rc')) 
first_link = first_result.find_element_by_tag_name('a') 
 
# Save the window opener (current window, do not mistaken with tab... not the same) 
main_window = browser.current_window_handle 
 
# Open the link in a new tab by sending key strokes on the element 
# Use: Keys.CONTROL + Keys.SHIFT + Keys.RETURN to open tab on top of the stack  
first_link.send_keys(Keys.CONTROL + Keys.RETURN) 
 
# Switch tab to the new tab, which we will assume is the next one on the right 
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB) 
 
# Put focus on current window which will, in fact, put focus on the current visible tab 
browser.switch_to_window(main_window) 
 
# do whatever you have to do on this page, we will just got to sleep for now 
sleep(2) 
 
# Close current tab 
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w') 
 
# alternatively, use this, but it was reported that it doesn't always work 
# driver.close() 
 
# Put focus on current window which will be the window opener 
browser.switch_to_window(main_window) 

如果您使用的是 Mac,这可能行不通,但在评论中也给出了解决方法。

或者,this SO answer通过使用选项卡的窗口名称还有另一种解决方法。


更新:如评论中所述,用户使用 Linux(不在 OP 中)。使用以下组合键代替上面代码中提到的默认组合:Keys.CONTROL + Keys.SHIFT + Keys.RETURN。