关于使用Selenium获取网页控制台的数据

背景:

需要获取网页的控制台的数据,如下图

在此文章将使用到 Pycharm 和 Selenium4

Pycharm安装
Selenium安装

python 复制代码
from selenium import webdriver
from selenium.webdriver.common.by import By
import time

# 创建浏览器对象
browser = webdriver.Chrome()


# 打开页面
browser.get("https://www.baidu.com")

# 元素定位 (多种,以下使用XPATH)
# 注:线上大部分的定位函数为find_element_by_id,可能是旧版本Selenium的函数,现使用.find_element(By.___ , "")
browser.find_element(By.XPATH,"//*[@id='kw").send_keys("填入内容") # 填入输入框
browser.find_element(By.XPATH,"//*[@id='su").click() # 点击搜索

##延迟代码结束运行
time.sleep(1000)

关闭浏览器
browser.quit()

Selenium中的find_element方法 //供参考

这里使用Chrome有一个技巧可以直接复制元素的信息

到此我们已经完成了一部分简单的自动化操作了

接下来我们需要记录和获取控制台的信息,这部分参考可参考
jmeter-调用python脚本

python 复制代码
import json
import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

options = Options()

caps = {
    "browserName": "chrome",
    'goog:loggingPrefs': {'performance': 'ALL'}  # 开启日志性能监听
}

# 将caps添加到options中
for key, value in caps.items():
    options.set_capability(key, value)

browser = webdriver.Chrome(options=options)

# 打开页面
browser.get("https://www.baidu.com")
# 填入输入框
browser.find_element(By.XPATH,"//*[@id='kw").send_keys("填入内容") 
# 点击搜索
browser.find_element(By.XPATH,"//*[@id='su").click() 

# 停留10秒加载数据
time.sleep(10)

# 获取名称为 performance 的日志
performance_log = browser.get_log('performance')

# 打印获取的数据,有需要再进一步筛选
print(performance_log)
相关推荐
我的xiaodoujiao5 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 31--开源电商商城系统项目实战--加入购物车、提交订单测试场景
python·学习·测试工具·pytest
测试人社区—52725 小时前
你的单元测试真的“单元”吗?
前端·人工智能·git·测试工具·单元测试·自动化·log4j
测试人社区—52729 小时前
破茧成蝶:DevOps流水线测试环节的效能跃迁之路
运维·前端·人工智能·git·测试工具·自动化·devops
白露与泡影10 小时前
从 JDK 8 到 JDK 18,Java 垃圾回收的十次进化
java·开发语言·测试工具
我的xiaodoujiao11 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 30--开源电商商城系统项目实战--配置测试环境地址
python·学习·测试工具·pytest
测试秃头怪20 小时前
2026最新软件测试面试八股文(含答案+文档)
自动化测试·软件测试·python·功能测试·测试工具·面试·职场和发展
测试老哥1 天前
Postman接口测试基本操作
自动化测试·软件测试·python·测试工具·测试用例·接口测试·postman
零基础的修炼1 天前
测试开发---性能测试概念篇
压力测试
西江649761 天前
【个人博客系统—测试报告】
python·功能测试·jmeter·pycharm·postman
月亮!1 天前
移动端测试重磅升级:跨平台自动化测试框架深度对比
运维·网络·人工智能·测试工具·容器·自动化·测试用例