我想用 selenium 多任务测试,不想开多个浏览器,只想在一个浏览器里面多标签操作。我参照网上的代码写了如下的。可是多窗口总是不行,二个关键字都输入到一个标签了。有人帮忙看看吗?
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.by import By
from concurrent.futures.thread import ThreadPoolExecutor
url = 'https://www.baidu.com/'
keys = ['java', 'python', 'go']
def openwin(url):
newwindow = f'window.open("{url}")'
browser.execute_script(newwindow)
browser.switch_to.window(browser.window_handles[-1])
handle = browser.current_window_handle
sleep(2)
print(handle)
return handle
def outer(keyword):
def browser_work(res):
handle=res.result()
print(handle)
if browser.current_window_handle != handle:
browser.switch_to.window(handle) # 移动句柄,对新打开页面进行操作
print('browser is working...')
el_location = browser.find_element(By.XPATH, '//*[@id="kw"]')
el_location.clear()
el_location.send_keys(keyword)
el_location = browser.find_element(By.XPATH, '//*[@id="su"]')
el_location.click()
sleep(3)
browser.close()
browser.switch_to.window(browser.window_handles[0])
return browser_work
ts=[]
options = Options()
options.add_argument("--no-sandbox")
options.add_argument('--disable-gpu')
options.add_argument('window-size=1920x1080')
browser = webdriver.Chrome(options=options)
browser.get("https://bing.com/")
POOL = ThreadPoolExecutor(2)
for i in keys:
futrue = POOL.submit(openwin,url)
futrue.add_done_callback(outer(i))
1
theohateonion 2022-10-21 11:04:52 +08:00
|
2
doyel 2022-10-21 11:09:40 +08:00
用 headless 去请求吧
|
3
brucmao 2022-10-21 12:25:45 +08:00
|
4
ClericPy 2022-10-21 20:38:33 +08:00
chrome 原生 CDP 做过不同标签页并行执行不同命令, selenium 还真不清楚它这 send_keys 是 dispatch Event 还是走驱动模拟点击...
PS: 多 tab 当心那个同域名连接约束, 反正我之前超过 6 个 Tab 时候第七个就一直等待连接, 最后用多个浏览器上下文解决的 |
6
jshmysq 2022-10-27 13:29:06 +08:00
这种方式不行的,会打架
看看 grid |