【问题标题】:Scrapy Extract ld+JSONScrapy 提取 ld+JSON
【发布时间】:2017-12-09 21:22:48
【问题描述】:

如何提取名称和url?

quotes_spiders.py

import scrapy
import json

class QuotesSpider(scrapy.Spider):
    name = "quotes"
    start_urls = ["http://www.lazada.com.my/shop-power-banks2/?price=1572-1572"]

    def parse(self, response):
        data = json.loads(response.xpath('//script[@type="application/ld+json"]//text()').extract_first())
        //how to extract the name and url?
        yield data

要提取的数据

<script type="application/ld+json">{"@context":"https://schema.org","@type":"ItemList","itemListElement":[{"@type":"Product","image":"http://my-live-02.slatic.net/p/2/test-product-0601-7378-08684315-8be741b9107b9ace2f2fe68d9c9fd61a-webp-catalog_233.jpg","name":"test product 0601","offers":{"@type":"Offer","availability":"https://schema.org/InStock","price":"99999.00","priceCurrency":"RM"},"url":"http://www.lazada.com.my/test-product-0601-51348680.html?ff=1"}]}</script>

【问题讨论】:

  • 您当前的代码会发生什么情况?与您的预期不同吗?你能展示你得到什么和缺少什么吗?
  • 没关系,我已经解决了...感谢您的帮助
  • 你是怎么解决的??

标签: python json xpath scrapy


【解决方案1】:

这行代码返回一个包含你想要的数据的字典:

data = json.loads(response.xpath('//script[@type="application/ld+json"]//text()').extract_first())

您需要做的就是像这样访问它:

name = data['itemListElement'][0]['name']
url = data['itemListElement'][0]['url']

鉴于微数据包含一个列表,您需要检查您是否引用了列表中的正确产品。

【讨论】:

    【解决方案2】:

    一个非常简单的解决方案是使用https://github.com/scrapinghub/extruct。它处理提取结构化数据的所有困难部分。

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 2018-01-27
      • 1970-01-01
      • 2016-11-23
      • 2016-11-22
      • 2022-01-22
      • 1970-01-01
      • 2022-10-12
      • 1970-01-01
      相关资源
      最近更新 更多