Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

Selenium won't open a new URL in a new tab (Python & Chrome)

I want to open quite a few URLs in different tabs using Selenium WebDriver & Python.

I am not sure what is going wrong:

driver = webdriver.Chrome()
driver.get(url1)
time.sleep(5)
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL+'t')
url2 = 'https://www.google.com'
driver.get(item2)

I looked up tutorials and it seems to me as though this code should do what I want. What actually happens is the browser opens, url1 opens as it should, a new tab opens as it should but url2 then loads in the original tab instead of the new one (even though the new tab appears to be the active one).

(I am using Chrome because when using Firefox I can't get it to load any URLs at all. Firefox opens but does not get the url requested. I have tried to find a solution to this but to no avail.)

Is there anything I can change in my code to get the new URL to open in the new tab?

Thanks for your help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is a simple way, platform independent:

Code:

driver.execute_script("window.open('http://google.com', 'new_window')")

Switching back to the original tab:

Code:

driver.switch_to_window(driver.window_handles[0])

Checking the current title to be sure you are on the right page:

Code:

driver.title

For everything else, have fun!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...