使用Scrapy抓取时,某些“非常用字符”编码不正确

时间:2019-07-04 06:32:12

标签: python encoding utf-8 scrapy

我已经使用Scrapy来获取电影数据,但是其中一些具有特殊字符,这些字符编码不正确。

例如,有一部电影在网站上具有链接: Pokémon: Detective Pikachu

获取电影名称时与“é”字符冲突。

使用终端命令“ scrapy crawl movie -o films.json”将所有数据添加到json文件中。

如果在Scrapy的settings.py中提供了非FEED_EXPORT_ENCODING,则将神奇宝贝一词写成json文件中的"Pok\u00e9mon"

如果使用FEED_EXPORT_ENCODING ='utf-8',则名称将写为“Pokémon”

spider中的解析方法如下:

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')",但没有成功。

感谢您的帮助!谢谢大家!

1 个答案:

答案 0 :(得分:1)

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

enter image description here