当使用第三方库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 코딩에 대한 이해가 조금 부족한 것 같습니다.
1. 요청과 요청 모두 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')
r.content[:1000].decode('utf-8')
r.content 인쇄[: 1000].decode('utf-8').encode('gbk')
스크래피 여부에 관계없이 디코드와 인코딩을 사용하세요.