首頁  >  問答  >  主體

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,
        }
PHPzPHPz2741 天前1067

全部回覆(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
  • 取消回覆