Python:如何在Python Selenium中打开新标签页而不等待当前标签页加载

kxxlusnw  于 2022-12-04  发布在  Python
关注(0)|答案(3)|浏览(215)

我打开10标签(相同的网址)在铬浏览器成功。但问题是,我的网址需要1分钟加载页面,我不想等待1分钟,在每个标签。
我需要让它加载,并希望打开另一个选项卡,我知道最终选项卡强制需要一分钟加载,但没有问题,但我不想等待1分钟,为每个选项卡。
我可以做些甚么来达到这个目标呢?
我用过time.sleep()WebDriverWaitdriver.switch_to.window(x),但是没有用。
提前致谢
这是我的代码:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common import window
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec

options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
options.add_argument("start-maximized")
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
url = 'http://my_url/Index'
driver.get(url)
for _ in range(10):
    driver.get(url)
    driver.switch_to.new_window(window.WindowTypes.TAB)
lc8prwob

lc8prwob1#

看起来每次打开URL时都需要创建一个线程

import threading

def main(url)
  # use a different driver for each thread
  options = webdriver.ChromeOptions()
  options.add_experimental_option("detach", True)
  options.add_argument("start-maximized")
  driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
  driver.get(url)
  rand_function1
  return

url = "http://my_url/Index"
for t in range(10):
   t = threading.Thread(target=main, args=[url])
   t.start()
gt0wga4j

gt0wga4j2#

要摆脱等待打开的标签页加载的状态,您需要应用NONEPageLoadStrategy。默认情况下使用NORMALPageLoadStrategy。根据定义,在本例中为WebDriver should wait for the document readiness state to be "complete" after navigation,而您需要WebDriver should not wait on the document readiness state after a navigation event策略。
要将此PageLoadStrategy应用于您的代码,应将此添加到您的代码中:

caps = DesiredCapabilities().CHROME
caps["pageLoadStrategy"] = "none"

这是我这边整个代码的样子。它按预期工作

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.chrome.service import Service

options = Options()
options.add_argument("--start-maximized")

caps = DesiredCapabilities().CHROME
caps["pageLoadStrategy"] = "none"
s = Service('C:\webdrivers\chromedriver.exe')

driver = webdriver.Chrome(options=options, desired_capabilities=caps, service=s)
hmae6n7t

hmae6n7t3#

使用Python Selenium打开一个/多个新选项卡而不等待当前选项卡页面加载的最快方法是使用 execute_script() 方法,如下所示:

  • 代码块:
driver = webdriver.Chrome(service=s, options=options)
driver.get('https://stackoverflow.com/')
for _ in range(10):
    driver.execute_script("window.open('','_blank');")
  • 浏览器快照:

相关问题