【问题标题】:Extracting HTML fields through XPath通过 XPath 提取 HTML 字段
【发布时间】:2012-12-17 14:02:36
【问题描述】:

我有这个查询,它会提取“喜欢”超过 5 次的帖子。

//div[@class="pin"]
[.//span[@class = "LikesCount"]
[substring-before(normalize-space(text())," ") > 5]

我想提取和存储附加信息,例如标题、img url、编号、repin 编号……

如何将它们全部提取出来?

  • 多个 XPath 查询?
  • 在使用 php 和 php 函数进行迭代时挖掘结果帖子的节点?
  • ...

遵循标记示例:

<div class="pin">

<p class="description">gorgeous couch <a href="#">#modern</a></p>

[...]

<div class="PinHolder">
<a href="/pin/56787645270909880/" class="PinImage ImgLink">
    <img src="http://media-cache-ec3.pinterest.com/upload/56787645270909880_d7AaHYHA_b.jpg" 
         alt="Krizia" 
         data-componenttype="MODAL_PIN" 
         class="PinImageImg" 
         style="height: 288px;">
</a>
</div>

<p class="stats colorless">
    <span class="LikesCount"> 
        22 likes 
    </span>
    <span class="RepinsCount">
        6 repins
    </span>
</p>

[...]

</div>

【问题讨论】:

  • “最佳”方式对您意味着什么?
  • 一旦我得到了正确的帖子,我不知道哪种方法是提取存储和组织所有这些信息的最佳方法

标签: php dom xpath simplexml


【解决方案1】:

由于您已经在代码中使用 XPath,我建议您也使用 XPath 提取该信息。下面是一个关于如何提取描述的示例。

<?php 

// will store the posts as assoc arrays
$mostLikedPostsArr = array();

// call your fictional load function
$doc = load_html('whatever');

// create a XPath selector
$selector = new DOMXPath($doc);

// this your query from above
$query = '//div[@class="pin"][.//span[@class = "LikesCount"][substring-before(normalize-space(text())," ") > 5]';

// getting the most liked posts
$mostLikedPosts = $selector->query($query);

// now iterate through the post nodes
foreach($mostLikedPosts as $post) {

    // assoc array for a post
    $postArr = array();

    // you can do 'relative' queries once having a reference to $post
    // note $post as the second parameter to $selector->query()

    // lets extract the description for example
    $result = $selector->query('p[@class = "description"]', $post);
    // just using nodeValue might be ok for text only nodes.
    // to properly flatten the <a> tags inside the descriptions 
    // it will take further attention.
    $postArr['description'] = $result->item(0)->nodeValue;

    // ...

    $mostLikedPostsArr []= $postArr;
}

【讨论】:

  • 看起来很酷!!但我不明白你如何以这种方式提取描述: $node 定义在哪里?为什么不分配查询结果?
  • 抱歉没有尝试编码。当然 $node 没有定义。 ;) 更新它。
  • 请注意,您不应该在未检查 $result->length 之前使用 $result->item(0)。只是想让示例尽可能简单。
  • 有趣的是,我放了一个 echo 而不是数组赋值。但它总是显示相同的描述。看起来“相对”查询根本不是相对的。奇怪
  • 是的,没有// 的查询将从 $post 节点解析。当使用// 时,文档根是起点。看DOMXPath::query的手册。该参数称为contextnode。
猜你喜欢
  • 2018-04-06
  • 2018-08-10
  • 2020-07-19
  • 1970-01-01
  • 2023-03-17
  • 2015-06-09
  • 2015-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多