5

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 ?

1 Answer 1

8

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.