我试图在Selenium中制作多个标签,并同时在每个标签上打开一个页面。这是代码。
CHROME_DRIVER_PATH = "C:/chromedriver.exe"
from selenium import webdriver
import threading
driver = webdriver.Chrome(CHROME_DRIVER_PATH)
links = ["https://www.google.com/",
"https://stackoverflow.com/",
"https://www.reddit.com/",
"https://edition.cnn.com/"]
def open_page(url, tab_index):
driver.switch_to_window(handles[tab_index])
driver.get(url)
return
# open a blank tab for every link in the list
for link in range(len(links)-1 ): # 1 less because first tab is already opened
driver.execute_script("window.open();")
handles = driver.window_handles # get handles
all_threads = []
for i in range(0, len(links)):
current_thread = threading.Thread(target=open_page, args=(links[i], i,))
all_threads.append(current_thread)
current_thread.start()
for thr in all_threads:
thr.join()
执行没有错误,据我所知,从逻辑上讲应该可以正常工作。但是,该程序的效果并不像我想象的那样。它一次只打开一页,有时甚至不切换选项卡...是否有我在代码中没有意识到的问题,或者Selenium无法使用线程?
答案 0 :(得分:3)
无需切换到新窗口即可获取URL,您可以在下面尝试在新标签页中依次打开每个URL:
links = ["https://www.google.com/",
"https://stackoverflow.com/",
"https://www.reddit.com/",
"https://edition.cnn.com/"]
# Open all URLs in new tabs
for link in links:
driver.execute_script("window.open('{}');".format(link))
# Closing main (empty) tab
driver.close()
现在,您可以照常处理(如果需要)driver.window_handles
中的所有窗口