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
1.1k views
in Technique[技术] by (71.8m points)

google chrome - Python -- Opening multiple tabs using Selenium

I am using Python. I am trying to open two tabs on chrome, each to a different website. This is my code:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time


browser=webdriver.Chrome()
browser.get('http:/reddit.com')
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
time.sleep(3)
browser.get('http://bing.com')

When I run it, the first tab is opened to reddit.com, and then another tab opens to my default webpage, and then bing.com is opened in the original tab. I want the first tab to go to Reddit and the second tab to go to bing, but browser.get('website') only acts on the first tab.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

To interact with a window, you need to set the context to that window with driver.switch_to.window. It would also be easier to open a new tab with a script injection:

browser=webdriver.Chrome()

#first tab
browser.get('http:/reddit.com')

#second tab
browser.execute_script("window.open('about:blank', 'tab2');")
browser.switch_to.window("tab2")
browser.get('http://bing.com')

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

...