Home > Net >  Read page source of window opened in new tab
Read page source of window opened in new tab

Time:12-26

Code for trying to read elements of window opened in new tab. I always get to see message "Not entered"

webd = webdriver.Chrome(service=s, options=options)
url = "some url"
webd.execute_script("window.open('"   url   "','_blank');")
if len(webd.find_elements(By.TAG_NAME, "pre")) > 0:
    print("entered")
else:
    print("not enetered")

It part works perfectly fine if opened in same tab like below

webd = webdriver.Chrome(service=s, options=options)
url = "some url"
webd.get(url)
if len(webd.find_elements(By.TAG_NAME, "pre")) > 0:
    print("entered")
else:
    print("not enetered")

Am I missing something in former part?

CodePudding user response:

It would be best to switch windows or tabs before locating your element. From your comment, I am guessing that you have already done that. If so, it's an exception about finding the element because I run the following code that proves that the switching window works perfectly.

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome(ChromeDriverManager().install())

url = "https://www.google.com/"

driver.execute_script("window.open('"   url   "','_blank');")
tab_list = driver.window_handles

try:
   driver.switch_to.window(tab_list[1])
   element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//img')))
   print("Element Found")
except Exception as e:
   print("No Element")

And to put more light on the situation when you use the execute script method, selenium tries to find elements immediately in the blank window and doesn't find any, thus throwing errors. Even if you switch windows instantly, it doesn't wait for elements to load on the other window. You have to wait manually. But on the second code snippet, selenium waits for the page to load entirely and then finds the element, so it works perfectly.

CodePudding user response:

webd = webdriver.Chrome(service=s, options=options)
url = "some url"
webd.execute_script("window.open('"   url   "','_blank');")
# Get a list of all open windows
window_handles = webd.window_handles

# Switch to the new window
webd.switch_to.window(window_handles[-1])
if len(webd.find_elements(By.TAG_NAME, "pre")) > 0:
    print("entered")
else:
    print("not enetered")
  • Related