如何使用Selenium测量页面下载时间 [英] How to measure page download time with Selenium

查看:64
本文介绍了如何使用Selenium测量页面下载时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Selenium(Python)测量网站的页面下载和渲染时间?目前我有类似

How do I go about measuring page download+rendering time of a website in selenium (Python)? Currently I have something like

... # set up web driver and loop through a list of domain names

print currDomainName
start = datetime.now()
browser.get(currDomainName)
end = datetime.now()

... # do something with the time diff

但是它不能完全正常工作,因为在页面渲染完成之前不能保证get()会阻塞.它的官方文档也说

But it doesn't quite work because get() isn't guaranteed to block until page render is complete. Its official doc also says

在某些情况下,WebDriver可能会在页面完成甚至加载之前返回控制权.

In some circumstances, WebDriver may return control before the page has finished, or even started, loading.

实际上,在我的简短测试代码中,print语句实际上可以在Webdriver中的一个完成加载之前向下打印两个或三个url.

In fact, in my short test code the print statement could literally be printing two or three urls further down before the one in webdriver finishes loading.

我知道在某些网页元素上使用显式等待可以强制执行阻止,但是有通用的方法吗?我正在大约数千个网站上对此进行测量,因此拥有独立于Web内容的东西将是很棒的.

I know using explicit wait on certain webpage elements can enforce blocking, but is there a generic way of doing this? I'm measuring this on about a few thousand websites, so it would be great to have something independent from the web content.

推荐答案

确保所有内容均已加载的唯一方法是使用

Only way how to make sure that everything is loaded is to use ExplicitWait. Downside is that you have to know which element slows the rendering of each particular page but this is the only way how to keep your measure precise.

start = datetime.now()
browser.get(currDomainName)
WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, 
   "reallyHugeImageId")))
end = datetime.now()

请注意,time.sleep()会中断您的测量,因为您将始终等待准确的时间.因此,唯一的方法是研究即使WebDriver返回了哪些元素仍未呈现,并通过ExpectedCondition等待它们.

Note that time.sleep() would break your measures because you would always wait exact time. So only way is to investigate which elements are not yet rendered even if the WebDriver returns and wait from them through ExpectedCondition.

这篇关于如何使用Selenium测量页面下载时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆