登录

python - 使用Scrapy中的Request的时候,怎么把拿到的内容编码转换为utf-8?

当使用第三方库requests的时候,可以这样转换:

import requests

html = requests.get('http://example.com')
html.encoding = 'utf-8'

问题:
使用Scrapy中的Request的时候,怎么把拿到的内容编码转换为utf-8?

demo:

import scrapy


class StackOverflowSpider(scrapy.Spider):
    name = 'stackoverflow'
    start_urls = ['http://stackoverflow.com/questions?sort=votes']

    def parse(self, response):
        for href in response.css('.question-summary h3 a::attr(href)'):
            full_url = response.urljoin(href.extract())
            yield scrapy.Request(full_url, callback=self.parse_question)

    def parse_question(self, response):
        yield {
            'title': response.css('h1 a::text').extract_first(),
            'votes': response.css('.question .vote-count-post::text').extract_first(),
            'body': response.css('.question .post-text').extract_first(),
            'tags': response.css('.question .post-tag::text').extract(),
            'link': response.url,
        }
# Python
PHPzhongPHPzhong2165 天前726 次浏览

全部回复(2) 我要回复

  • 大家讲道理

    大家讲道理2017-04-18 09:08:14

    试着回答你的问题,感觉你对python的编码理解有点跑偏。
    1、无论requests还是Request,都是一种http协议的实现包而已。
    包返回报文的编码来源于HTTP协议所访问的网站,在http协议的头部会写明编码格式。
    譬如 如下代码:
    r=requests.get('http://www.baidu.com')
    print r.headers['Content-Type']
    输出:
    text/html;charset=UTF-8
    这里表明了应答报文的utf-8格式。
    scrapy.Request也是一样。
    2、如果返回的charset=gbk2312,你可以根据你的代码需要,确定是否转码成你需要的编码。
    r=requests.get('http://www.baidu.com')
    print r.content[:1000].decode('utf-8')
    print r.content[:1000].decode('utf-8').encode('gbk')

    回复
    0
  • PHP中文网

    PHP中文网2017-04-18 09:08:14

    就是用decode和encode啊,也不管是不是scrapy的事。

    回复
    0
  • 取消回复发送