Home > front end >  Python Selenium Chrome loop through links in tabs
Python Selenium Chrome loop through links in tabs

Time:01-15

Hi I have a main web page that opens in the main tab to accept cookies, and the rest of the links that should loop through open and close in tabs:

links = ['https://www.deviceinfo.me/','https://www.deviceinfo.me/','https://www.deviceinfo.me/','https://www.deviceinfo.me/','https://www.deviceinfo.me/']

driver = webdriver.Chrome(executable_path=r'C:\ProgramFiles(x86)\chromedriver.exe')
driver.get('https://www.deviceinfo.me/') #open the main tab

for link in links: 
    driver.execute_script("window.open();") # open a new tab
    driver.switch_to.window(driver.window_handles[1])   # switch to the tab 1
    driver.get(link)
    driver.close() # close tab 1

But this doesn't work, any suggestions how to fix this?

thank you.

CodePudding user response:

This should work:

You basically got to the window_handle[1] but did not switch back to parent window and hence the issue

links = ['https://www.deviceinfo.me/','https://www.deviceinfo.me/','https://www.deviceinfo.me/','https://www.deviceinfo.me/','https://www.deviceinfo.me/']

driver = webdriver.Chrome(executable_path=r'C:\ProgramFiles(x86)\chromedriver.exe')
driver.get('https://www.deviceinfo.me/') #open the main tab

for link in links: 
    driver.execute_script("window.open();") # open a new tab
    driver.switch_to.window(driver.window_handles[1])   # switch to the tab 1
    driver.get(link)
    driver.close() # close tab 1
    driver.switch_to.window(driver.window_handles[0])
  •  Tags:  
  • Related