python - 使用Scrapy中的Request的时候,怎么把拿到的内容编码转换为utf-8?
PHPz
PHPz 2017-04-18 09:06:14
0
2
1058

当使用第三方库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,
        }
PHPz
PHPz

学习是最好的投资!

全部回复(2)
大家讲道理

试着回答你的问题,感觉你对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')

洪涛

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!