【问题标题】:Scrapy (python) responses alternating between bytes and utf8Scrapy(python)响应在字节和 utf8 之间交替
【发布时间】:2019-08-14 01:55:22
【问题描述】:

我使用的是scrapy网络爬虫,在抓取网站时,响应在html和字节之间交替,它们是utf8编码的,但我在尝试解码时收到并出错。

我尝试了多种不同的标头进行编码,接受 gzip、deflate、text/html;charset=utf-8, br 但它们一直给我同样的问题。

"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
"Accept-Language": "en-US,en;q=0.9",
"Accept-Encoding": "text/html;charset=utf-8",

接收 html 而不是字节,(这里是接收到的字节的 sn-p 与 html 相比)。 预期反应

b'<!DOCTYPE html><html lang="en" xmlns:og="http://opengraphprotocol.org/schema/"><head><link rel="appl'

实际反应

b'\x93b\x92\x12)\x1d@I\xc1y\x00\x00h\xeb\x9d\x875\xaa\xd7\xc0\xfc\xb0q\x00\x00\xf0\x15\x0f\xdbF\xb1\xf3\x0f

【问题讨论】:

  • 它看起来像压缩响应。不要使用"accepting gzip, br",只保留"accepting deflate"
  • 你也可以尝试解压缩 - 如果服务器接受br 然后import brotli; print(brotli.decompress(b'\x93b\x92\x12...'))
  • 我希望 Scrapy 能够自动解压缩。您是否禁用了HttpCompressionMiddleware
  • brotli.error: BrotliDecompress failed brotli 不起作用

标签: python web web-scraping scrapy http-headers


【解决方案1】:

"Accept-Encoding": "text/html;charset=utf-8" 看起来不对。试试"Accept-Encoding": "gzip",或者完全删除它。

【讨论】:

  • 非常感谢,我 99% 都尝试过,但最终成功了,谢谢。也可能已经将 COOKIE_ENABLED 设置为 true
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多