简体   繁体   中英

How to close newly constructed tab using selenium, chrome driver and python

I am trying to scrape data from a website, there is an url which lands me a particular page, there we have links of some items, if I click on those links, it opens in a new tab, and I can extract data from there,

But after extracting the data, I want to close the tab return to the main page and click on another link.

I am using selenium with chrome web driver. I have tried following code:

#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.

How to close newly constructed tab using selenium and python ?

You could try this solution.

# 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])  

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM