【问题标题】:Is there any solution to get loaded time?有什么解决方案可以获取加载时间吗?
【发布时间】:2021-04-12 12:17:18
【问题描述】:
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Firefox()
driver.get('https://pythonbasics.org')
timeout = 3
try:
    element_present = EC.presence_of_element_located((By.ID, 'main'))
    WebDriverWait(driver, timeout).until(element_present)
except TimeoutException:
    print("Timed out waiting for page to load")
finally:
    print("Page loaded")

这是我的代码,我想获取等待时间,例如如果加载某个 xpath 类需要 1 分钟,那么获取这个时间

【问题讨论】:

  • 你想获取页面渲染时间还是在页面上定位元素的时间?
  • 定位元素的时间

标签: python python-3.x selenium selenium-webdriver selenium-chromedriver


【解决方案1】:

你可以这样做:

import time

driver = webdriver.Firefox()
driver.get('https://pythonbasics.org')
timeout = 100

try:
    start_time = time.time()
    element_present = EC.presence_of_element_located((By.ID, 'main'))
    WebDriverWait(driver, timeout).until(element_present)
    diff_time = time.time() - start_time
    print("It takes {} seconds to find element".format(diff_time))

except TimeoutException:
    print("Timed out waiting for page to load")
finally:
    print("Page loaded")

【讨论】:

  • @user15528966 你说的不现实是什么意思?
  • @user15528966 它给了我大约 0.02 秒。页面不包含任何(或至少是复杂的)JavaScript,所以一切似乎都很好
  • 我想测试幻灯片是否加载成功,有时滑块加载缓慢.....这是个好主意吗?用 xpath 检查?
  • @user15528966 什么是“滑块”?你的意思还是this page
【解决方案2】:

@jaSON 给出的答案是正确的。但是还有另一种选择,即来自 python 库 timeit 的 timeit 方法。 您可以通过多种方式使用它。 我会给你正确解释文章的超链接。
[Python Timit()]:https://www.guru99.com/timeit-python-examples.html#:~:text=Python%20timeit()%20is%20a,given%20set%20of%20code%20snippets.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-17
    • 2014-11-14
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 2011-08-15
    • 2023-01-20
    • 2021-12-01
    相关资源
    最近更新 更多