json脚本/标记中的Scrapy产品数据不能作为目标

7fyelxc5  于 2022-11-09  发布在  其他
关注(0)|答案(2)|浏览(139)

我 可以 解析 脚本 中 的 json 数据 , 但是 我 不能 针对 特定 的 标记 。
If it would be a "normal" script type like "application/ld+json", it would be pretty easy to collect what I need. But I cannot address the script name, cause there is no name 😅 So I used the XPATH selector to the script via dev tools.
因此 , 我 从 product link 读取 Scrapy shell 中 的 json 数据

scrapy shell 'https://www.electronic4you.de/makita-dmp180z-akku-kompressor-189153.html' ...
...
>>> response.xpath('//*[@id="root-wrapper"]/div/script[5]/text()').get()

中 的 每 一 个
当然 , 我 会 得到 脚本 中 的 所有 数据 。 结果 显示 :
[ ' new E4uTrack ( " 查看 项目 " , {" 货币 " : " 欧元 " , " 价值 " : " 49 " , " 页面 类型 " : " 产品 " , " 标题 " : " 牧 田 DMP180Z Akku-Kompressor " , " 项目 " : [ {" 项目 名称 " : " 牧 田 DMP180Z Akku-Kompressor " , " 项目 编号 " : " 189153 " , " 编号 " : " 189153 " , " 项目 mpn " : " DMP180Z " , " 项目 _ gtin " : " 0088381898263 " , " 项目 _ 品牌 " : " 牧 田 " , " google _ business _ vertical " : " 零售 " , " 价格 " : " 49 " , " 货币 " : " 欧元 "
通常 , 我 会 以 一 个 值 为 目标 , 例如 , " item _ name " 中 的 值 , 其中 包含 :

scrapy shell 'https://www.electronic4you.de/makita-dmp180z-akku-kompressor-189153.html' ...
...
>>> script_tag = response.xpath('//*[@id="root-wrapper"]/div/script[5]/text()').get()
>>> import json
>>> json.loads(script_tag)["items"]["item_name"]

格式
可是 ... ...
输出 显示 :
文件 " " , 第 1 行 json . loads ( 脚本 标记 ) [ " 项目 名称 " ]
缩进 错误 :意外 缩进
我 有 两 个 问题 。
我 用 xpath 选择 器 正确 地 定位 脚本 了 吗 ? 我 如何 从 这个 脚本 中 只 定位 我 需要 的 标签 ?

tmb3ates

tmb3ates1#

您必须遍历ResultSet并提取所需的数据

import scrapy
import json
class TestSpider(scrapy.Spider):
    name = 'test'
    start_urls = ['https://www.electronic4you.de/makita-dmp180z-akku-kompressor-189153.html']

    def parse(self, response):

        script_tag =  response.xpath('(//*[@id="root-wrapper"]/div/script)[5]/text()').re_first(r'E4uTrack\("view_item",(.+?)\)$')
        json_data= json.loads(script_tag)

        for item in json_data["items"]:
            yield {
                'Name':item["item_name"]
                }

输出:

{'Name': 'Makita DMP180Z Akku-Kompressor'}
rkttyhzu

rkttyhzu2#

您需要使用正则表达式来清除XPath结果:

json_raw = response.xpath('//script[contains(., "E4uTrack(\"view_item\"")]/text()').re_first(r'E4uTrack\("view_item",(.+?)\)$')
data = json.loads(json_raw)

相关问题