Selenium-wire 响应对象 - 以字符串而不是字节形式获取响应主体的方法

hp2*_*505 7 selenium response httpresponse utf-8 seleniumwire

我想以 selenium-wire 中的字符串形式获取响应主体,最终将其解析为 JSON。

response.body在 selenium-wire 中给出字节字符串。我尝试解码它,response.body.decode('utf-8')但这给出了解码错误。

有人可以帮我弄这个吗?我对这两种解决方案都很好:

  1. 将字节字符串解码为普通字符串的方法
  2. 首先将响应正文作为普通字符串获取的方法

小智 10

默认情况下,selenium-wire 以字节形式返回主体响应。

文档说:

“响应正文为字节。如果响应没有正文,则正文的值将为空,即 b''。有时正文可能已被服务器编码 - 例如压缩。您可以使用disable_encoding选项来防止这种情况。您可以手动解码编码的响应正文:

from seleniumwire.utils import decode

body = decode(response.body, response.headers.get('Content-Encoding', 'identity'))
Run Code Online (Sandbox Code Playgroud)

这对我有用。


hp2*_*505 0

我找到了一种方法来做到这一点(不是理想的方法)在制作 selenium webdriver 对象时,您可以传递一个参数,您options可以在其中明确告诉它提供解码后的请求和响应对象,而不是作为字节。

  • `选项= {'disable_encoding':True}` (2认同)