首页 > 解决方案 > 如何从 json 文件中删除 \n

问题描述

当我尝试使用终端将抓取的数据保存在 json 文件中时,在 Brand 和 Brand name ({"Brand": "\n Libra\n ", "Price": "$24.95"},) 后面有一个 \n。如何解决这个问题呢。

import scrapy


class GlassSpider(scrapy.Spider):
    name = 'glass'
    allowed_domains = ['www.glassesshop.com']
    start_urls = ['https://www.glassesshop.com/bestsellers/']

    def parse(self, response):
        for item in response.xpath("//div[@class='col-12 pb-5 mb-lg-3 col-lg-4 product-list-row text-center product-list-item']"):
            yield {
                'Brand': item.xpath(".//div[@class='p-title']/a/text()").get(),
                'Price': item.xpath(".//div[@class='product-title p-tab p-tab-13145']/span/text()").get()
            }

标签: python-3.xscrapy

解决方案


您可以使用str replace方法:

...
    yield {
        'Brand': item.xpath(".//div[@class='p-title']/a/text()").get("").replace("\n",""),
        'Price': item.xpath(".//div[@class='product-title p-tab p-tab-13145']/span/text()").get("").replace("\n","")
        }

推荐阅读