首页 > 解决方案 > 如何从scrapy中替换或删除特殊字符?

问题描述

我刚开始学习scrapy并试图让蜘蛛从网站上获取一些信息并尝试替换删除“short_descr”中的特殊字符

import scrapy


class TravelspudSpider(scrapy.Spider):
    name = 'travelSpud'
    allowed_domains = ['www.tripadvisor.ca']
    start_urls = [
        'https://www.tripadvisor.ca/Attractions-g294265-Activities-c57-Singapore.html/'
    ]
    base_url = 'https://www.tripadvisor.ca'

    def parse(self, response, **kwargs):

        for items in response.xpath('//div[@class= "_19L437XW _1qhi5DVB CO7bjfl5"]'):

            yield {
                'name':        items.xpath('.//span/div[@class= "_1gpq3zsA _1zP41Z7X"]/text()').extract()[1],

                'reviews':     items.xpath('.//span[@class= "DrjyGw-P _26S7gyB4 _14_buatE _1dimhEoy"]/text()').extract(),

                'rating':      items.xpath('.//a/div[@class= "zTTYS8QR"]/svg/@title').extract(),

                'short_descr': items.xpath('.//div[@class= "_3W_31Rvp _1nUIPWja _17LAEUXp _2b3s5IMB"]'
                                       '/div[@class="DrjyGw-P _26S7gyB4 _3SccQt-T"]/text()').extract(),

                'place':       items.xpath('.//div[@class= "ZtPwio2G"]'
                                       '/div'
                                       '/div[@class= "DrjyGw-P _26S7gyB4 _3SccQt-T"]/text()').extract(),

                'cost':        items.xpath('.//div[@class= "DrjyGw-P _26S7gyB4 _3SccQt-T"]'
                                       '/div[@class= "DrjyGw-P _1SRa-qNz _2AAjjcx8"]'
                                       '/text()').extract(),
            }

        next_page_partial_url = response.css("div._1I73Kb0a").css("div._3djM0GaD").xpath('.//a/@href').extract_first()

        if next_page_partial_url is not None:

            next_page_url = self.base_url + next_page_partial_url
            yield scrapy.Request(next_page_url, callback=self.parse)

我要替换的字符是Hiking Trails • Scenic Walking Areas. 中间的点在 csv 文件中解码,因为• Everyting else 就像一个魅力。

我尝试使用.replace(),但出现错误:

AttributeError: 'list' object has no attribute 'replace'

任何帮助,将不胜感激

标签: web-scrapingscrapyspecial-characters

解决方案


如果您删除这些特殊字符只是因为它们在 CSV 文件中奇怪地出现,那么我建议不要删除它们。只需在settings.py文件中添加以下行。

FEED_EXPORT_ENCODING = 'utf-8-sig'

这将打印 CSV 文件中的特殊字符。


推荐阅读