如何将 scrapy.http.headers.Headers 类型转换为字符串类型



当我使用Python Scrapy时,我需要获取response.headers的内容并将其转换为json格式,但是response.headers的类型不是字符串。

这是我的代码:

def start_requests(self):
url = example.com
yield scrapy.Request(url, callback=self.example)
def example(self,response):
print(type(response.headers),response.headers,sep='nn')

结果:

<class 'scrapy.http.headers.Headers'> 
{b'Date': [b'Sun, 09 Feb 2020 11:40:32 GMT'], b'Content-Type': [b'text/html; charset=utf-8'], b'Last-Modified': [b'Thu, 06 Feb 2020 12:46:22 GMT'], b'Access-Control-Allow-Origin': [b'*'], b'Expires': [b'Sun, 09 Feb 2020 11:25:33 GMT'], b'Cache-Control': [b'max-age=600'], b'X-Proxy-Cache': [b'MISS'], b'X-Github-Request-Id': [b'7404:79E4:296ECA:2ED9E5:5E3FE9D4'], b'Via': [b'1.1 varnish'], b'Age': [b'20'], b'X-Served-By': [b'cache-sjc10050-SJC'], b'X-Cache': [b'HIT'], b'X-Cache-Hits': [b'1'], b'X-Timer': [b'S1581248432.467223,VS0,VE0'], b'Vary': [b'Accept-Encoding'], b'X-Fastly-Request-Id': [b'ea8aae70ba4691d060aeca764f445527279e23e7'], b'Cf-Cache-Status': [b'DYNAMIC'], b'Expect-Ct': [b'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"'], b'Server': [b'cloudflare'], b'Cf-Ray': [b'562591aedc3ded7b-SJC']}

当我使用json.dumps(response.headers)时,它总是提示TypeError: keys must be str, int, float, bool or None, not bytes

我刚刚遇到了同样的问题,并在这里找到了这个问题:

刮擦/http/headers.py

代码非常简单:

page_headers = response.headers.to_unicode_dict()

到目前为止,我的案件效果很好。

with response.headers Scrapy 返回字节文字。您必须将字典内容转换为字符串文字。以下代码应完成这项工作:

# -*- coding: UTF-8 -*-
import scrapy
class Example(scrapy.Spider):
name = 'test'    
def start_requests(self):
url = 'http://www.example.com'
yield scrapy.Request(url, callback=self.example)
def example(self,response):
print(self.convert(response.headers))
def convert(self, data):
if isinstance(data, bytes):  return data.decode('ascii')
if isinstance(data, list):   return data.pop().decode('ascii')
if isinstance(data, dict):   return dict(map(self.convert, data.items()))
if isinstance(data, tuple):  return map(self.convert, data)
return data

最新更新