【问题标题】:simplexml doesnt load <a> tag classes?simplexml 不加载 <a> 标记类?
【发布时间】:2015-10-20 16:20:46
【问题描述】:

我有一点 php 从页面中抓取 html 并将其加载到 simplexml 对象中。但是它没有在

中获取元素的类

php

//load the html page with curl
$html = curl_exec($ch);
curl_close($ch);

$doc = new DOMDocument();
$doc->loadHTML($html);
$sxml = simplexml_import_dom($doc);

页面 html。如果我执行 $html 的 var_dump 会显示它已被抓取并存在于 $html 中

    <li class="large">
        <a style="" id="ref_3" class="off" href="#" onmouseover="highlightme('07');return false;" onclick="req('379');return false;" title="">07</a>
    </li>

$doc 和 $sxml 的 var_dump(下)表明现在缺少 'off' 类。不幸的是,我需要根据这个类来处理页面。

            [8]=>
             object(SimpleXMLElement)#50 (2) {
              ["@attributes"]=>
              array(1) {
                ["class"]=>
                string(16) "large"
              }
              ["a"]=>
              string(2) "08"
            }

【问题讨论】:

  • 您想从您的文档中获取所有具有off 类的a 元素吗?或所有li 类为“大”的a 元素?
  • 我需要找到 li 中所有的 a 元素,其中 class 为 large。在我的另一个问题中,我们提取了所有人员及其工作时间,我需要提取那些“关闭”的字符串。问题是如您在上面的示例中看到的,simplxml 没有提取 的类,只是字符串:-( 此处为完整的 html,带有关闭类 bl.ocks.org/hotnuts21/2a3658c34f61872b6709
  • 我在您的文档中看不到任何“关闭”类
  • 您可能需要强制刷新我编辑的页面。

标签: php html web-scraping simpledom


【解决方案1】:

使用 simplexml_load_filexpath,查看内联 cmets。

一旦你找到了你需要的元素,你所追求的就是这个

$row->a->attributes()->class=="off"

以及下面的完整代码:

// let's take all the divs that have the class "stff_grid"
$divs = $xml->xpath("//*[@class='stff_grid']");

// for each of these elements, let's print out the value inside the first p tag
foreach($divs as $div){
    print $div->p->a . PHP_EOL;

    // now for each li tag let's print out the contents inside the a tag
    foreach ($div->ul->li as $row){

        // same as before
        print "  - " . $row->a;
        if ($row->a->attributes()->class=="off") print " *off*";
        print PHP_EOL;

        // or shorter
        // print "  - " . $row->a . (($row->a->attributes()->class=="off")?" *off*":"") . PHP_EOL;

    }
}
/* this outputs the following
Person 1
  - 1 hr *off*
  - 2 hr
  - 3 hr *off*
  - 4 hr
  - 5 hr
  - 6 hr *off*
  - 7 hr *off*
  - 8 hr
Person 2
  - 1 hr
  - 2 hr
  - 3 hr
  - 4 hr
  - 5 hr
  - 6 hr
  - 7 hr *off*
  - 8 hr *off*
Person 3
  - 1 hr
  - 2 hr
  - 3 hr
  - 4 hr *off*
  - 5 hr
  - 6 hr
  - 7 hr *off*
  - 8 hr
*/

【讨论】:

  • 好吧,这行得通,做一个 var_dump 表明属性确实存在于对象中,而它们不在我原来的帖子中,这很奇怪。我需要向后工作以了解为什么我的原始对象没有加载这些属性。感谢您的所有帮助,我已经创建并将奖励您的所有帮助。
  • 欢迎您@PaulM!但赏金并不是真正必要的。
  • 对于其他任何人来说,似乎只是从 simplexml_load_dom 切换到 simplexml_load_file 确保所有元素的所有属性都在对象中,以便我可以访问它们。
猜你喜欢
  • 2012-02-10
  • 2013-08-01
  • 2012-08-14
  • 1970-01-01
  • 2013-09-30
  • 1970-01-01
  • 1970-01-01
  • 2019-11-26
  • 2012-11-03
相关资源
最近更新 更多