我使用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"}]
我唯一的抱怨是我想让“豆豆名字”出现在“价格”之前。在
这就是我的项目.py文件:
^{pr2}$这是我的蜘蛛的代码:
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"}]
谢谢。在
对象在JSON格式中是无序的,因此键的顺序没有区别。在
另外,我建议不要输出JSON。使用JSON行(默认格式),每行输出一个单独的JSON编码对象。拥有一个巨大的JSON编码对象将使读取刮取的项目效率低下。在
JSON对象中的顺序并没有明显的区别。在这里依赖顺序是错误的,如果顺序很重要,则应该使用数组。在
如果您坚持要管理订单,可以查看pprint库。在
相关问题 更多 >
编程相关推荐