我 可以 解析 脚本 中 的 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 选择 器 正确 地 定位 脚本 了 吗 ? 我 如何 从 这个 脚本 中 只 定位 我 需要 的 标签 ?
2条答案
按热度按时间tmb3ates1#
您必须遍历ResultSet并提取所需的数据
输出:
rkttyhzu2#
您需要使用正则表达式来清除XPath结果: