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

当使用第三方库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. リクエストとリクエストはどちらも http プロトコルの単なる実装パッケージです。
パケット返信メッセージのエンコードは、HTTP プロトコルが訪問する Web サイトから取得され、エンコード形式は 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
洪涛

Scrapy であるかどうかに関係なく、デコードとエンコードを使用してください。

いいねを押す +0
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!