如何使用 selenium、chrome 驱动程序和 python 关闭新建的选项卡

Kal*_*lol 4 python selenium web-scraping selenium-chromedriver selenium-webdriver

我正在尝试从网站上抓取数据,有一个网址可以让我进入特定页面,那里有一些项目的链接,如果我点击这些链接,它会在一个新选项卡中打开,我可以从那里提取数据,

但是提取数据后,我想关闭选项卡返回主页并单击另一个链接。

我正在使用 selenium 和 chrome web 驱动程序。我尝试过以下代码:

#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.
Run Code Online (Sandbox Code Playgroud)

如何使用 selenium 和 python 关闭新建的选项卡?

Dai*_*tas 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])  
Run Code Online (Sandbox Code Playgroud)

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