【问题标题】:formatting JSON created by scraping a website with Python and Scrapy格式化通过使用 Python 和 Scrapy 抓取网站创建的 JSON
【发布时间】:2014-01-14 05:32:56
【问题描述】:

我使用 Scrapy 和 Python 抓取了一个网站,并使用以下命令将输出保存到 JSON 文件中:

$ scrapy crawl wcr -o top_selling_beans.json -t json
$ cat top_selling_beans.json 
[{"price": "$17.75", "bean_name": "Espresso Torro"},
{"price": "$18.75", "bean_name": "Sulawesi Toarco AA Tana Toraja"},
{"price": "$17.75", "bean_name": "Costa Rica La Minita"},
{"price": "$17.75", "bean_name": "Guatemala Acatenango Finca El Carmen"},
{"price": "$18.25", "bean_name": "Ethiopia Dry-Process Yirga Cheffe Konga"}]

我唯一的抱怨是我希望“bean_name”出现在“price”之前。

这是我的 items.py 文件中的内容:

from scrapy.item import Item, Field

class WestCoastRoastingItem(Item):
    bean_name = Field()
    price = Field()

这是我的蜘蛛的代码:

from scrapy.spider import BaseSpider
from scrapy.selector import Selector

from westcoastroasters.items import WestCoastRoastingItem

class WCRSpider(BaseSpider):
  name = "wcr"
  start_urls = ["http://www.westcoastroasting.com"]

  def parse(self, response):
    # Pull out the names and prices for the top sellers
    sel = Selector(response)
    top_sellers = sel.xpath(
      '//div[@id="SideTopSellers"]/div[@class="BlockContent"]/ul/li/div[@class="ProductDetails"]'
    )
    bean_names = top_sellers.xpath('strong/a/text()').extract()
    bean_prices = top_sellers.xpath('div[@class="ProductPriceRating"]/em/text()').extract()

    # Pass data to items
    items = []
    for name, price in zip(bean_names, bean_prices):
      item = WestCoastRoastingItem()
      item['bean_name'] = name
      item['price'] = price
      items.append(item)
    return items

当然,也许我太挑剔了? JSON 文件中键值对的顺序有什么真正的区别吗?如果是这样,我怎样才能让输出看起来像这样:

[{ "bean_name": "Espresso Torro", "price": "$17.75"}]

谢谢。

【问题讨论】:

    标签: python json scrapy


    【解决方案1】:

    JSON 对象中的顺序显然没有区别。在这里依赖顺序是错误的,如果顺序很重要,您应该使用数组。

    如果您坚持要管理订单,可以查看 pprint 库。

    【讨论】:

    • 同样值得注意的是,即使您确实在 JSON 编码的数据中强制排序,只要您将该数据导入 Python 或 JavaScript 或任何其他语言用它做任何事情,你最终会得到一个忽略顺序的 dict/Object/hash/whatever…
    【解决方案2】:

    对象在 JSON 格式中是无序的,因此键的顺序没有区别。

    另外,我建议不要输出 JSON。使用 JSON 行(默认格式),每行输出一个单独的 JSON 编码对象。拥有一个巨大的 JSON 编码对象会使读取抓取的项目效率低下。

    【讨论】:

      猜你喜欢
      • 2014-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-09
      • 2020-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多