Home > Mobile >  Selenium script searches previous tab's HTML after opening a new tab
Selenium script searches previous tab's HTML after opening a new tab

Time:05-09

After opening a new tab using selenium, I tried to look for an element in the new tab – but the script is still searching on the html script from the previous tab. How do I make it so that after I open a new tab, it searches the open tab's HTML instead of a previous one's?

Below is my code (it doesn't work since I try and search for an element on the new tab, but the script searches for it on the first tab).

options = webdriver.ChromeOptions() 
options.add_argument("user-data-dir=C:\\Users\\jack_l\\AppData\\Local\\Google\\Chrome\\User Data")
options.add_argument(r'--profile-directory=Profile 8')
driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)

#Opens the Chrome browser
driver.get("https://www.beatstars.com/")

#Opens a new tab on the browser and goes to that URL
driver.execute_script("window.open('https://www.tunestotube.com/', 'new window')")

#Doesn't work since it's searching for a "tunestotube" element on "beatstars"
theText = driver.find_element(By.XPATH, "/html/body/div[2]/div[2]/div[2]").text

Any help would be greatly appreciated.

CodePudding user response:

Found a solution: You need to switch to the new window

Below is code that gets a website on the first tab, opens a new tab with another website, and then can read/find elements in that new tab.

#Gets a browser and sets the window to a variable
driver.get("https://www.exampleWebsiteForFirstTab.com/")
window_before = driver.window_handles[0]

#Open a new tab and sets the window to a variable
driver.execute_script("window.open('https://www.exampleWebsiteForSecondTab.com/', 'new window')")
window_after = driver.window_handles[1]

#Switches the current window to the new tab
driver.switch_to.window(window_after)

###DO WHATEVER YOU WANT IN THE NEW TAB

#Switches the current window to the old tab
driver.switch_to.window(window_before)

Hopefully this helps anyone who had the same problem I did!

CodePudding user response:

driver.execute_script("window.open('https://www.tunestotube.com/', 'new window')")
driver.switch_to.window( driver.window_handles[1])

theText = driver.find_element(By.XPATH, "/html/body/div[2]/div[2]/div[2]").text

When you open a tab you get a handle you need to switch back to the previous handle and then find your element.

  • Related