playwright python版本学习四:playwright脚本运行过程中监控 API(接口) 的请求相关信息

playwright 执行脚本时监控脚本请求信息

1,编写一个响应方法,用来设置要监控的内容

# xxxx/xx 表示你想监控url中包含某些信息的请求,你也可以不加判断,监控所有
def check_response(response):
    response.finished()
    if "/xxxxxx/xxx/search" in response.url:
        logging.info("URL:{}".format(response.request.url))
        logging.info("method:{}".format(response.request.method))
        logging.info("status:{}".format(response.status))
        logging.info("timing:{} 毫秒".format(response.request.timing['responseEnd']))

2, 使用这个定义好的方法

# 注意:在page定义完成后,直接放那儿就行了
page.on('response',check_response)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Playwright 是一个用于自动化浏览器的工具,它主要用于模拟用户在浏览器的操作,例如点击、输入文本等。如果您要获取接口响应,可以使用其他工具,例如 Python 的 `requests` 模块。 要在 Playwright 获取接口 URL 和响应结果,您可以使用 `request` 事件和 `response` 对象。在该事件,您可以捕获每个请求并检查其 URL,然后在响应对象查找响应数据。以下是一个示例: ``` import asyncio from playwright.async_api import async_playwright, Playwright async def main(): async with async_playwright() as p: browser = await p.chromium.launch() page = await browser.new_page() # Define a callback function to handle requests async def handle_request(request): # Print the request URL print("Request URL:", request.url) # Continue the request and get the response response = await request.continue_() # Print the response body print("Response Body:", await response.text()) # Return the response return response # Add the callback function to the page await page.route("**/*", handle_request) # Navigate to a page that makes a request await page.goto("https://example.com") # Close the browser await browser.close() asyncio.run(main()) ``` 在上面的示例,我们首先创建一个 Playwright 实例,并在 Chromium 浏览器打开一个新页面。然后,我们定义一个回调函数 `handle_request` 来处理每个请求。在该函数,我们首先打印请求 URL,然后继续请求获取响应。然后,我们打印响应体,并返回响应对象。接下来,我们使用 `page.route()` 方法将回调函数添加到页面,以便它可以处理每个请求。最后,我们使用 `page.goto()` 方法导航到一个页面,该页面会发出一个请求。最后,我们关闭浏览器实例并退出。 注意,`route()` 方法只能捕获页面请求,而不能捕获浏览器的其他请求(例如图片、脚本、样式表等)。如果您需要捕获所有请求,请使用 `context.route()` 方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

走走又停停,人生路上皆风景

不同的你我,不同的风景,祝幸福

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值