使用python语言的selenium脚本编写一段代码:使用edge浏览器打开一个网页,打开100次,精确获取每次的加载时长,放在一个列表里,最后求平均加载时长
时间: 2024-09-27 17:08:02 浏览: 42
Edge浏览器驱动程序 python程序使用使用selenium打开浏览器访问网页
在Python中,我们可以使用Selenium库结合Edge浏览器和WebDriverWait来实现这个任务。首先,确保已安装了`selenium`, `webdriver_manager`以及对应的Edge浏览器驱动。这里以Windows环境为例,下载对应的`msedgedriver.exe`。
```python
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import time
# 初始化driver
def setup_driver():
options = webdriver.EdgeOptions()
# 如果需要设置特定的隐身模式,可以添加下面这行
# options.add_argument("headless")
driver = webdriver.Edge(options=options)
return driver
# 计算并存储页面加载时间
def measure_load_time(driver):
url = "https://example.com" # 替换为你想要打开的网页地址
driver.get(url)
try:
element_to_wait = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.TAG_NAME, "html")) # 等待页面元素加载完成
)
start_time = time.time()
while True:
if time.time() - start_time > 5: # 设置一个较短的超时时间,防止无限循环
break
load_time = time.time() - start_time
except Exception as e:
print(f"Failed to measure load time: {e}")
load_time = None
return load_time
# 打开和测量页面100次
load_times = []
for _ in range(100):
driver = setup_driver()
load_time = measure_load_time(driver)
if load_time is not None:
load_times.append(load_time)
driver.quit()
# 求平均加载时长
if load_times:
average_load_time = sum(load_times) / len(load_times)
print(f"Average page loading time: {average_load_time} seconds")
else:
print("No valid load times recorded.")
阅读全文