selenium获取网络响应的正文

本文介绍了一种利用Selenium WebDriver结合Chrome DevTools Protocol的方法,用于抓取指定API接口的响应正文。通过设置特定参数并解析性能日志,最终实现了准确获取目标API返回的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有时我们爬虫时,需要获取到页面的api接口响应正文

 下面我们上具体代码:

from selenium import webdriver 
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import time
import json

caps = {
    'browserName': 'chrome',
    'loggingPrefs': {
        'browser': 'ALL',
        'driver': 'ALL',
        'performance': 'ALL',
    },
    'goog:chromeOptions': {
        'perfLoggingPrefs': {
            'enableNetwork': True,
        },
        'w3c': False,
    },
}
driver = webdriver.Chrome(desired_capabilities=caps)

driver.get('http://127.0.0.1:8000/apiGet?id=1&pid=334')
# 必须等待一定的时间,不然会报错提示获取不到日志信息,因为絮叨等所有请求结束才能获取日志信息
time.sleep(3)

request_log = driver.get_log('performance')

到这里,我们成功获取到了网页加载的所有资源,资源都在request_log里面,现在我们就需要筛选出来我们需要的资源requestId

for i in range(len(request_log)):
    message = json.loads(request_log[i]['message'])
    message = message['message']['params']
    # .get() 方式获取是了避免字段不存在时报错
    request = message.get('request')
    if(request is None):
        continue

    url = request.get('url')
    if(url == "http://127.0.0.1:8000/apiGet?id=1&pid=334"):
        # 得到requestId
        print(message['requestId'])
        # 通过requestId获取接口内容
        content = driver.execute_cdp_cmd('Network.getResponseBody', {'requestId': message['requestId']})
        print(content)
        break

 这里最主要是driver里面的 execute_cdp_cmd方法,我们可以根据此方法来获取网页的请求包,具体文档参考此

查看的源码是

def execute_cdp_cmd(self, cmd, cmd_args):
    """
    Execute Chrome Devtools Protocol command and get returned result
    The command and command args should follow chrome devtools protocol domains/commands, refer to link
    https://chromedevtools.github.io/devtools-protocol/

    :Args:
     - cmd: A str, command name
     - cmd_args: A dict, command args. empty dict {} if there is no command args

    :Usage:
        driver.execute_cdp_cmd('Network.getResponseBody', {'requestId': requestId})

    :Returns:
        A dict, empty dict {} if there is no result to return.
        For example to getResponseBody:

        {'base64Encoded': False, 'body': 'response body string'}

    """
    return self.execute("executeCdpCommand", {'cmd': cmd, 'params': cmd_args})['value']

结果就是这样

 

### 使用Selenium在Java中获取HTTP响应值 由于Selenium WebDriver本身并不直接支持获取HTTP响应码或响应头的功能,因此通常需要借助其他工具来实现这一目标。一种常见的方法是利用浏览器开发者工具协议(CDP, Chrome DevTools Protocol),这可以通过启用性能日志记录并解析其中的数据来间接获得HTTP请求的相关信息。 另一种方式是在测试环境中集成代理服务器,比如BrowserMob Proxy,它能够捕获所有的网络流量,并允许访问详细的HTTP消息细节,包括状态码和头部信息等[^1]。 下面是采用BrowserMob Proxy配合Selenium Java API的一个简单例子: ```java import net.lightbody.bmp.BrowserMobProxyServer; import net.lightbody.bmp.client.ClientUtil; import org.openqa.selenium.Proxy; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class HttpResponseExample { public static void main(String[] args) throws InterruptedException { BrowserMobProxyServer proxy = new BrowserMobProxyServer(); proxy.start(0); // 获取 Selenium 代理对象 Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy); System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { String url = "http://example.com"; // 设置代理 ((org.openqa.selenium.remote.RemoteWebDriver) driver).setFileDetector(new org.openqa.selenium.remote.LocalFileDetector()); ((org.openqa.selenium.remote.DesiredCapabilities)((org.openqa.selenium.remote.Augmenter())new Augmenter()).augment(driver)).setCapability(CapabilityType.PROXY, seleniumProxy); // 开始捕捉哈希表中的所有请求 proxy.newHar("test"); driver.get(url); Thread.sleep(2000); // 等待页面加载完成 // 停止捕捉并将结果保存到变量har中 var har = proxy.getHar(); // 遍历HAR文件条目以找到特定URL的状态码和其他详情 for (var entry : har.getLog().getEntries()) { if(entry.getRequest().getUrl().equals(url)){ int statusCode = entry.getResponse().getStatus(); System.out.println("Status Code: "+statusCode); break; } } } finally { driver.quit(); proxy.stop(); } } } ``` 此代码片段展示了如何设置BrowserMob Proxy并与Selenium WebDriver一起工作,从而可以监控指定网站上的HTTP交互情况,并从中提取出所需的响应数据[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值