Skip to main content
 首页 » 编程设计

python之单击 pyqt 按钮后立即停止加载页面 selenium

2025年02月15日8shangdawei

from selenium import webdriver 
driver=webdriver.Firefox() 
driver.get("https://9gag.com")#page that take too much time to load 

由于此页面加载时间太长,我想在单击 pyQt 按钮并开始填写表单后立即停止加载该页面。我不想使用 browser.set_page_load_timeout,因为我不知道何时停止

def stop_page_load(): 
    global driver 
    """What should be the definition so that as soon as I 
       click btn4,browser should stop loading""" 
 
 
 
###w is a QWidget 
btn4=QtWidgets.QPushButton("stop page load",w) 
btn4.pressed.connect(stop_page_load) 

请您参考如下方法:

您需要使用 pageLoadStrategy 作为 none 加载 firefox。然后你可以停止页面加载,但这样做的副作用是你需要自己在所有地方等待页面加载,因为 selenium 不会自动为你做那件事。您还可以使用 eager 而不是 none ,它会等待页面的 readyState 为真,但仍然会给您一些时间来加载页面

import time 
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities 
from selenium import webdriver 
 
cap = DesiredCapabilities.FIREFOX 
cap["pageLoadStrategy"] = "none" 
print(DesiredCapabilities.FIREFOX) 
driver = webdriver.Firefox(capabilities=cap) 
 
driver.get("https://9gag.com")#page that take too much time to load 
 
time.sleep(1) 
driver.execute_script("window.stop();") 

Edit-1:旧版本的 firefox

对于旧版本的 firefox,您需要设置配置文件首选项,因为这些浏览器不使用 marrionette

FirefoxProfile profile = new FirefoxProfile(); 
profile.setPreference("webdriver.load.strategy", "unstable"); 
WebDriver driver = new FirefoxDriver(profile);