如何使用simple_html_DOM找到标签

时间:2016-02-25 07:09:43

标签: php parsing dom html-parsing

我尝试使用php simple_html_dom来解析带有此标记的网页:

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

其中data-tn-component =&#34; organicJob&#34;是我想要解析的标识符,我似乎无法以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,但我仍然不了解如何格式化查找字符串。 我做错了什么?

1 个答案:

答案 0 :(得分:1)

您的选择器是正确的但我在您的代码中看到了其他问题

1)您的包含.php中的include 'simple_html_dom';遗失了{/ 1}}

include '/absolute_path/simple_html_dom.php';

2)通过网址加载内容使用file_get_html函数代替$html->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 ;
}
相关问题