如何使用Selenium、Chrome Driver和Python关闭新建的选项卡

4
我正在尝试从一个网站上爬取数据。有一个URL可以让我进入到一个特定的页面,那里有一些物品的链接。如果我点击这些链接,它们会在新标签页中打开,然后我就可以从这里提取数据。
但是,在提取完数据后,我想关闭该标签页并返回到主页面,然后再点击另一个链接。我正在使用Chrome Web Driver的Selenium。我尝试了以下代码:
#links which lands me to a new tab
browser.find_element_by_xpath('//*[@id="data"]/div[1]/div[2]/a').click()

browser.switch_to.window(browser.window_handles[0])
browser.close() #it closes the main page, not the new tab I want
and following code,
browser.find_element_by_css_selector('body').send_keys(Keys.CONTROL + 'w')  #this code didn't work.

如何使用selenium和python关闭新建立的选项卡?
1个回答

7
您可以尝试这个解决方案。
# New tabs will be the last object in window_handles
driver.switch_to.window(driver.window_handles[-1])

# close the tab
driver.close()

# switch to the main window
driver.switch_to.window(driver.window_handles[0])  

参考: http://antlong.com/common-operations-working-with-tabs-in-webdriver/

这篇文章讲解了如何使用Webdriver处理浏览器标签页。它介绍了如何在当前标签页中打开链接、如何在新标签页中打开链接以及如何在多个标签页之间切换。此外,还提供了示例代码帮助读者更好地理解。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接