Hamita
Hamita

Reputation: 61

Switching to new window with selenium python

I have a list with all xpath of links

Here is my code:


original_window = driver.current_window_handle
for stat in stats:
  
     
     
     WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, stat))).click()
     WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
     for window_handle in driver.window_handles:
        if window_handle != original_window:
            driver.switch_to.window(window_handle)
            print(driver.current_url)
            driver.close()
            driver.switch_to.window(original_window)
            print(driver.current_url)
            break
            
     time.sleep(15)    

It works the first time but after that it gives me this error:

https://s5.sir.sportradar.com/sports4africa/fr/1/season/81152/headtohead/322375/90970/match/27122060
https://www.bountou1x2.com/sport.jsp
Traceback (most recent call last):
  File "c:\Users\Hama\Documents\Python project\test3.py", line 45, in <module>
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, stat))).click()
  File "C:\Users\Hama\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:

Here is how Stats is defined:

stats = []

for a in driver.find_elements_by_tag_name("tr"):
   aa = a.get_attribute("idavv")
   if aa is not None:
      aaa = "//*[@id=\"simple-row-box-prematch-" + aa + "\"]/td[6]/table/tbody/tr/td[1]"
     
      stats.append(aaa)
      

if i let only the click event the code works fine like this and opens all windows:

for stat in stats:
  
     
     
     WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, stat))).click()
     
     time.sleep(15)    

The error appears only when i try to switch from the old to new and from the new to old window, it works only the first time

I print the current url just to see if it's switching as it most

Help is appreciated, thanks to all of you

Upvotes: 0

Views: 661

Answers (1)

Hamita
Hamita

Reputation: 61

I found the solution to my problem, it was the frame, it works the first time because the frame was selected, everytime i switch back i must swith to the frame too so my code become:

 WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, stat))).click()
 WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
 for window_handle in driver.window_handles:
    if window_handle != original_window:
        driver.switch_to.window(window_handle)
        print(driver.current_url)
        driver.close()
        driver.switch_to.window(original_window)
        driver.switch_to.frame(driver.find_element_by_id("receiver"))
        
        break

Upvotes: 1

Related Questions