【问题标题】:CURL XPATH grab only the first divCURL XPATH 只抓取第一个 div
【发布时间】:2015-09-02 16:08:14
【问题描述】:

我正在尝试使用 XPath 获取网站上的最新消息。

新闻在许多具有相同名称的 div 中(以及一个名为“p_maj”的类) 这是 div 的示例:

<div class="p_maj">
  <h1>10 juin 2015</h1>
  <div class="z_b_important">
  <h2>Actualités du projet</h2>
  <p>some text</p>
  <p>some text</p>
  <h2>Version Cristal </h2>
  <p>some text</p>
  <h2>Barèmes</h2>
  <p>some text</p>
  <ul>
  <h2>Information</h2>
  <p>some text</p>
</div>
  
<div class="p_maj">
  <h1>03 juin 2015</h1>
  <h2>Barèmes</h2>
  <p>some text</p>
  <ul>
  <h2>Outils</h2>
  <p>some text</p>
</div>

我只想在我的网页上显示第一个 Div(最新发布的)。

这是我抓取 div 的 Curl 脚本(效果很好),但我找不到只有第一个的方法:

        <?php 
$curl = curl_init('http://mywebsite/maj.htm');
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);  
$result = curl_exec($curl);

$dom = new DOMDocument();
$res=$dom->loadHTML($result);
$xpath = new DomXPath($dom);
$class = 'p_maj';
$divs = $xpath->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $class ')]");

foreach($divs as $div) { 
echo $dom->saveXML($div);
}
?>

谁知道我可以使用什么样的指令?

很抱歉,Php 开发不是我的专长...

感谢所有愿意回答的人。

【问题讨论】:

    标签: php html curl xpath


    【解决方案1】:

    第一个 div 为 class="p_maj"

    //div[@class="p_maj"][1]
    

    【讨论】:

    • 你的意思是我应该重复这行 $divs = $xpath->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $class ')]"); with $divs = $xpath->query("//div[@class="p_maj"][1]");很抱歉,但这似乎不起作用。
    • Oups...对不起:我终于明白你告诉我的了。我将发布最终代码。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2020-03-27
    • 2013-11-30
    • 1970-01-01
    • 1970-01-01
    • 2023-01-24
    • 1970-01-01
    • 2011-07-21
    • 2017-06-22
    相关资源
    最近更新 更多