首页 > 解决方案 > 使用 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')"但没有成功。

我感谢您的帮助!多谢你们!

标签: pythonencodingutf-8scrapy

解决方案


使用编码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 文件

在此处输入图像描述


推荐阅读