格式化通过Python和Scrapy抓取网站创建的JSON

时间:2014-01-14 05:32:57

标签: python json scrapy

我使用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”出现在“价格”之前。

这是我的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"}]

感谢。

2 个答案:

答案 0 :(得分:1)

JSON对象中的顺序显然没有区别。依赖于此处的订单是一个错误,如果订单很重要,您应该使用数组。

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

答案 1 :(得分:1)

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

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