使用Scrapy刮取时,某些“非常用字符”编码错误

2024-04-24 06:53:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Scrapy来获取电影数据,但其中一些有特殊的字符,编码不正确。你知道吗

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

冲突是与“é”字符时,得到电影的名字。你知道吗

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

如果在Scrapy's设置.py,提供了非FEED\u EXPORT\u编码,单词Pokémon在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')",但没有成功。你知道吗

谢谢你的帮助!谢谢你们!你知道吗


Tags: 文件name信息json编码电影responsepage
1条回答
网友
1楼 · 发布于 2024-04-24 06:53:55

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

相关问题 更多 >