4

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 ?

Kallol
  • 2,089
  • 3
  • 18
  • 33

1 Answers1

7

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/