【问题标题】:how do I find a tag with simple_html_DOM如何找到带有 simple_html_DOM 的标签
【发布时间】:2016-06-07 19:59:04
【问题描述】:

我正在尝试使用simple_html_dom 和 php 来解析带有此标签的网页:

<div class="  row  result" id="p_a8a968e2788dad48" data-jk="a8a968e2788dad48" itemscope itemtype="http://schema.org/JobPosting" data-tn-component="organicJob">

其中 data-tn-component="organicJob" 是我要解析的标识符,我似乎无法以 simple_html_dom 识别的方式指定文本。

我尝试了一些类似的方法:

<?PHP
include 'simple_html_dom.php';
$f="http://www.indeed.com/jobs?q=Electrician&l=maine";
    $html->load_file($f);
        foreach($html->find('div[data-tn-component="organicJob"]') as $div)
              {
                 echo  $div->innertext ;
               }
?>

但是解析器没有找到任何结果,即使我知道它们在那里。可能我没有指定我正确找到的东西。 我正在查看the API,但我仍然不明白如何格式化查找字符串。 我做错了什么?

【问题讨论】:

    标签: php parsing dom html-parsing


    【解决方案1】:

    您的选择器是正确的,但我在您的代码中发现了其他问题

    1) 您在包含 include 'simple_html_dom'; 中缺少 .php 它应该是

    include '/absolute_path/simple_html_dom.php';
    

    2) 通过 url 加载内容使用 file_get_html 函数而不是 $html-&gt;load_file($f); 这是错误的,因为 php 不知道 $html 是 simple_html_dom 对象

    $html = file_get_html('http://www.google.com/');
    // then only call 
    $html->find( ...
    

    3) 在您提供的链接中:http://www.indeed.com/jobs?q=Electrician+Helper&l=maine 没有具有data-tn-component 属性的当前元素

    所以最终的代码应该是

    include '/absolute_path/simple_html_dom.php';
    $html = file_get_html('http://www.indeed.com/jobs?q=Electrician&l=maine');
    
    $html->load_file($f);
    foreach($html->find('div[data-tn-component="organicJob"]') as $div)
    {
        echo  $div->innertext ;
    }
    

    【讨论】:

    • 我的包含有一个错字,实际的代码有一个列表数组,我应该检查以确保我选择的那个是一个有效的列表,带有那个标签。即便如此,我仍然不确定 $html->find(... 之后应该发生什么
    • 我用最终代码更新了我的答案,请注意第 2 点)关于 whot 正确加载初始内容
    猜你喜欢
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 2021-06-24
    • 2022-01-26
    • 1970-01-01
    • 2017-05-03
    • 1970-01-01
    相关资源
    最近更新 更多