简体   繁体   中英

Using Python Selenium how to close the current tab which got opened when clicked a legal link on webpage

My scenario is on a webpage i am testing it has a link called "legal" when clicked will open a new tab where all the different pages links are available. once i am done working with that links have to close that tab and move to main tab where legal link was there.
I tried driver.close() it did not work.it is not closing the tab

Can anyone please help me how to close the correct tab and move to primary one

Try This Reference:-

https://gist.github.com/lrhache/7686903

1)Open a new window/tab by simulating a click on a link
2)Add a focus on this new tab
3)Wait for an element on the new page to be rendered (ui.WebDriverWait)
4)Do whatever you have to do on this new page
5)Close the tab
6)Return focus on original window opener

you can do it by using window_handels and switch_to.window() .

so before you click on "legal" button, store the current window handle by

parent_handle  = driver.window_handles[0]

after clicking the 'legal' button, you switch to new child handle

child_handle= [x for x in driver.window_handles if x != parent_handle][0]
driver.switch_to.window(child_handle) 

then add a sleep for a few seconds and do your work. then you can close the tab by

driver.close()

and now if want you can move to parent/previous website

driver.switch_to.window(parent_handle)

hope this helps.

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