【问题标题】:Convert Output of Xidel Pattern Match into Json Objects将 Xidel 模式匹配的输出转换为 Json 对象
【发布时间】:2018-03-06 23:33:33
【问题描述】:

好奇我是否可以使用文件中的 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

我只是在标准输出上得到所有变量的转储:

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 输出,但我特别有兴趣了解如何从存储在文件中的模式中获取该输出。

【问题讨论】:

    标签: xidel


    【解决方案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 调用它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-19
      • 2018-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多