1

我正在尝试使用 selenium 获取异步元素(MathJax 方程)加载时间。

我尝试编写一个python-selenium脚本来记录我的网站的加载时间,但是我的网站包含很多由Mathjax异步转换的方程,所以我无法正确记录。

我尝试先使用“performance.timing”记录加载时间,但它只能为我提供“加载时间”。

from selenium import webdriver
source = "url"
driver = webdriver.Chrome()
driver.get(source)
navigationStart = driver.execute_script("return window.performance.timing.navigationStart")
loadEventEnd = driver.execute_script("return window.performance.timing.loadEventEnd")
load_time = loadEventEnd - navigationStart

然后,我尝试找到“MathJax”的 ID 并等待一个 mathjax 元素(例如“MathJax-Element-1-Frame”)被加载

from selenium import webdriver
import time
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
source = "url"
driver = webdriver.Chrome()
begin = time.time()
driver.get(source)
locator = (By.ID, 'MathJax-Element-1-Frame')
WebDriverWait(driver, 20, 0.5).until(EC.presence_of_element_located(locator))
end = time.time()
finish_time = end - begin

但时间并不是绝对正确的。

4

1 回答 1

2

尝试使用datetime.utcnow()timedelta是:

将两个日期时间实例之间的差异表示为微秒分辨率的持续时间。

from datetime import datetime, timedelta
from selenium import webdriver
import time
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
source = "url"
driver = webdriver.Chrome()
begin = datetime.utcnow() + timedelta(1)
driver.get(source)
locator = (By.ID, 'MathJax-Element-1-Frame')
WebDriverWait(driver, 20, 0.5).until(EC.presence_of_element_located(locator))
end = datetime.utcnow() + timedelta(1)
finish_time = end - begin

更新

这是一个等待所有pendingRequests加载的函数。它也可能对您的情况有所帮助。

def wait_until_loaded(driver, seconds: int = 30) -> None:
    java_script_to_load = "var injector = window.angular.element('body').injector();"\
                                  " var $http = injector.get('$http');" \
                                  "return ($http.pendingRequests.length === 0);"
    end_time = datetime.utcnow() + timedelta(seconds=seconds)
    print("wait for All Elements....")
    while datetime.utcnow() <= end_time:
        try:
            if driver.execute_script(java_script_to_load):
                print(f"loaded in"
                      f" {datetime.utcnow() + timedelta(seconds=seconds) - end_time}seconds")
                sleep(1)
                return
        except WebDriverException:
            continue
        sleep(0.1)
    raise TimeoutError("waiting for elements for too long")

希望这对你有帮助!

于 2019-06-17T10:29:42.210 回答