Selenium + Python: How to stop page loading when certain element gets loaded?

前端 未结 1 386
夕颜
夕颜 2020-12-05 01:13

The implicit and explicit waits can be used when the page uses AJAX, but I want to stop the loading caused by driver.get() when sufficient elements are loaded.

相关标签:
1条回答
  • 2020-12-05 01:40

    Yes it's possible by setting the pageLoadStrategy capability to none. Then wait for an element to be present and call window.stop to stop the loading:

    from selenium import webdriver
    from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.by import By
    
    capa = DesiredCapabilities.CHROME
    capa["pageLoadStrategy"] = "none"
    
    driver = webdriver.Chrome(desired_capabilities=capa)
    wait = WebDriverWait(driver, 20)
    
    driver.get('http://stackoverflow.com/')
    
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#h-top-questions')))
    
    driver.execute_script("window.stop();")
    
    0 讨论(0)
提交回复
热议问题