【问题标题】:Seleniumwire get Response textSeleniumwire 获取响应文本
【发布时间】:2023-01-12 21:27:24
【问题描述】:

我正在使用 Selenium-wire 尝试读取某些网络流量的请求响应文本。我拥有的代码无法完全重现,因为该帐户位于付费专区后面。

我目前使用的硒线是:

for request in driver.requests:
    if request.method == 'POST' and request.headers['Content-Type'] == 'application/json':
        # The body is in bytes so convert to a string
        body = driver.last_request.body.decode('utf-8')
        # Load the JSON
        data = json.loads(body)

不幸的是,这是读取请求的有效负载

我正在尝试解析响应:

【问题讨论】:

    标签: python selenium selenium-webdriver seleniumwire


    【解决方案1】:

    你需要得到last_requestresponse

    body = driver.last_request.response.body.decode('utf-8')
    data = json.loads(body)
    

    【讨论】:

    • 谢谢 Yevhen,而不是最后一个请求,你知道我怎样才能得到倒数第二个请求吗?
    • 你应该可以通过 driver.requests[-2] 获得它。
    • 不要手动解码,只需使用response.json()
    • @wim 看起来它是selenium-wire自己对Response的实现,它没有.json()
    • 啊,哎呀,我以为他们取决于请求。
    【解决方案2】:

    我通常使用这3个步骤

    
    # I define the scopes to avoid other post requests that are not related
    # we can also use it to only select the required endpoints
    driver.scopes = [
         # .* is a regex stands for any char 0 or more times
        '.*stackoverflow.*',
        '.*github.*'
    ]
    
    # visit the page
    driver.get('LINK')
    
    # get the response
    response = driver.last_request # or driver.requests[-1]
    
    # get the json
    js = json.loads(
        decode(
            response.response.body,
            # get the encoding from the request
            response.headers.get('Content-Encoding', 'identity'),
        )
    )
    
    # this clears all the requests it's a good idea to do after each visit to the page
    del driver.requests
    

    欲了解更多信息,请访问doc

    【讨论】:

      猜你喜欢
      • 2014-06-15
      • 2017-06-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2018-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多