pythonselenium-chromedriverexecute-script

I need to give link from variable to execute_script(new window) in selenium python


I have a code that will open a new window and switched to before and after which like in code. But I what to give the link from variable why because if I have multiple links to search. For eg:search_url =["https://www.google.com", "https://www.yahoo.com", "https://www.bing.com"] Here is my code:

driver.get("http://www.facebook.com")
window_before = driver.window_handles[0]
window_before_title = driver.title
print(window_before_title)

#open a new window
driver.execute_script("window.open('http://www.twitter.com', 'new window')")
window_after = driver.window_handles[1]

#switch on to new child window
driver.switch_to.window(window_after)
time.sleep(10)

window_after_title = driver.title
print(window_after_title)

#Compare and verify that main window and child window title don't match
if window_before_title != window_after_title:
    print('Context switched to Twitter, so the title did not match')
else:
    print('Control did not switch to new window')

#switch back to original window
driver.switch_to.window(window_before)

#Verify that the title now match
if window_before_title == driver.title:
    print('Context returned to parent window. Title now match')
    print(driver.title)

From heredriver.execute_script("window.open('http://www.twitter.com', 'new window')") I want to use search_urlinstead of'http://www.twitter.com'.


Solution

  • Then if i understood correctly what you wrote instead of driver.execute_script("window.open('http://www.twitter.com', 'new window')") you have to write driver.execute_script("window.open('" + search_url[i] + "', 'new window')") in a for loop.