我正在尝试在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()
执行没有错误,据我了解,这在逻辑上应该可以正常工作。但是,该程序的效果并不像我想象的那样。它一次只打开一个页面,有时甚至不切换选项卡......是否存在我在代码中不知道的问题或线程不适用于硒?
无需切换到新窗口即可获取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
中的所有窗口