如何使用 selenium 记录 mathjax 加载时间

How can I use selenium to record mathjax loading time

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

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

我先尝试用"performance.timing"记录加载时间,但只能提供给我'load time'。

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

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

尝试将 datetime.utcnow()timedelta 一起使用,即:

A duration expressing the difference between two datetime instances to microsecond resolution.

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")

希望对您有所帮助!