好奇我是否可以使用文件中的Xidel模式将html列表转换为json对象数组。
给出这个例子HTML:
<div class="watch-sidebar-body">
<ul id="watch-related" class="video-list">
<li class="video-list-item">
<div class="content-wrapper">
<a href="/watch?v=XPt3uMaqG7c">
<span class="title">
10 Best Super Bowl 2018 Commercials
</span>
<span class="accessible-description">
- Duration: 11:07.
</span>
<span class="stat attribution"><span class="">Dalibor Truhlar</span></span>
<span class="stat view-count">546,346 views</span>
</a>
</div>
</li>
<li class="video-list-item">
...
从文件中使用此模式:
<ul id="watch-related" class="video-list">
<t:loop>
<li>
<a>
<span class="title">{$title}</span>
<span class="accessible-description">{$duration := extract(., "[0-9]+:[0-9]+")}</span>
<span>
<span>{$author}</span>
</span>
<span class="view-count">{$views := extract(., "[0-9,]+")}</span>
{url := @href}
</a>
</li>
</t:loop>
</ul>
我想生成以下json:
[{ "title" : "10 Best Super Bowl 2018 Commercials"
, "duration" : "11:07"
, "author" : "Dalibor Truhlar"
, "views" : "546,346"
, "url" : "/watch?v=XPt3uMaqG7c"
}
,{ "title" : "Funny Commercial Compilation"
, "duration" : "9:33"
, "author" : "Gaming Coyote"
, "views" : "9,449,290"
, "url" : "/watch?v=BTka0cgf99c"
}
...
模式与HTML正确匹配并提取数据,但我无法获得上面所示的json输出。
当我运行命令
时curl -s https://www.youtube.com/watch\?v\=HE9nLWFZ6ac | xidel - --silent --extract-file=yt.xq
我只是在stdout上转储所有变量:
title := 10 Best Super Bowl 2018 Commercials
duration := 11:07
author := Dalibor Truhlar
views := 548,710
url := /watch?v=XPt3uMaqG7c
title := Funny Commercial Compilation
duration := 9:33
author := Gaming Coyote
views := 9,451,516
url := /watch?v=BTka0cgf99c
但是我如何从这个到json对象的数组呢?
--output-format=json-wrapped
没有帮助,因为它将每个变量转换为它自己的数组,而不是将它们压缩成对象。
我知道可以在命令行上使用xpath表达式创建所需的json输出,但我特别感兴趣的是学习如何从存储在文件中的模式中获取该输出。
答案 0 :(得分:1)
您可以在模式中创建显式对象:
<ul id="watch-related" class="video-list">
<t:loop>
<li>
<a>
{$out := {}}
<span class="title">{$out.title}</span>
<span class="accessible-description">{$out.duration := extract(., "[0-9]+:[0-9]+")}</span>
<span>
<span>{$out.author}</span>
</span>
<span class="view-count">{$out.views := extract(., "[0-9,]+")}</span>
{$out.url := @href}
</a>
</li>
</t:loop>
</ul>
并使用| xidel - --silent --dot-notation=on --extract-file=yt.xq