python - 使用 Scrapy 抓取时,一些“非常规字符”编码不正确
问题描述
我使用 Scrapy 获取电影数据,但其中一些具有编码不正确的特殊字符。
例如,有一部电影在网站上有一个链接: 神奇宝贝:侦探皮卡丘
获取电影名称时与“é”字符发生冲突。
使用终端命令“scrapy crawl movie -o movies.json”将所有数据添加到 json 文件中
如果在 Scrapy 的 settings.py 中,未提供 FEED_EXPORT_ENCODING,则 Pokémon 这个词在 json 文件中写为"Pok\u00e9mon"
如果使用 FEED_EXPORT_ENCODING = 'utf-8',则名称被写为“Pokémon”
spider中的parse方法如下:
def parse(self, response):
base_link = 'http://www.the-numbers.com'
rows_in_big_table = response.xpath("//table/tr")
movie_name = onerow.xpath('td/b/a/text()').extract()[0]
movie_item['movie_name'] = movie_name
yield movie_budget_item
next_page =
response.xpath('//div[@class="pagination"]/a[@class="active"]/following-
sibling::a/@href').get()
if next_page is not None:
next_page = response.urljoin(next_page)
yield scrapy.Request(next_page, callback=self.parse)
作为额外信息,我有解析信息的 json 文件的信息:
<_io.TextIOWrapper name='movie.json' mode='r' encoding='cp1252'>
目标是获取"é"
单词中的字符"Pokémon"
。
您将如何解决这个问题以及为什么会发生这种情况,我一直在阅读大量有关编码和 Python 文档的信息,但我可以找到解决方案。
我也尝试过使用"unicodedata.normalize('NFKC', 'Pok\u00e9mon')"
但没有成功。
我感谢您的帮助!多谢你们!
解决方案
使用编码ISO-8859-1
import scrapy
from bad_encoding.items import BadEncodingItem
class MoviesSpider(scrapy.Spider):
name = 'movies'
allowed_domains = ['www.the-numbers.com']
start_urls = [
'https://www.the-numbers.com/box-office-records/domestic/all-movies/cumulative/all-time/301'
]
custom_settings = {'FEED_EXPORT_ENCODING': 'ISO-8859-1'}
def parse(self, response):
for row in response.xpath('//table/tbody/tr'):
items = BadEncodingItem()
items['Rank'] = row.xpath('.//td[1]/text()').get()
items['Released'] = row.xpath('.//td[2]/a/text()').get()
items['Movie'] = row.xpath('.//td[3]/b/a/text()').get()
items['Domestic'] = row.xpath('.//td[4]/text()').get()
items['International'] = row.xpath('.//td[5]/text()').get()
items['Worldwide'] = row.xpath('.//td[6]/text()').get()
yield items
这是我的 json 文件
推荐阅读
- sql-server - 我无法远程访问 SQL Server
- html - Esp32 和站点通信
- javascript - 使用 node.js 评估 javascript 源代码模块的最佳方法
- python - “找不到模块”python虚拟环境
- linux - 如何在不更新克隆它的本地存储库的情况下设置 git 存储库的远程 url?
- tcl - TCL - 尝试并行执行 proc 但出现奇怪的 Java 错误
- linux - 如何查看没有文件类型的可执行文件
- python - NOT NULL 约束失败:KNB_balance.user_id Django
- react-native - 使用 3 个不同的按钮更改状态的值(React Native)
- javascript - 如何在具有特定纬度/经度边界的 openlayers 地图上放置 div?