【问题标题】:Extracting data from HTML using Simple HTML DOM Parser使用 Simple HTML DOM Parser 从 HTML 中提取数据
【发布时间】:2013-11-07 18:42:01
【问题描述】:

对于一个大学项目,我正在创建一个包含一些后端算法的网站,并在演示环境中测试这些算法,我需要大量假数据。为了获得这些数据,我打算抓取一些网站。其中一个网站是 freelance.com。为了提取数据,我使用了简单的 HTML DOM 解析器,但到目前为止,我一直未能成功获得所需的数据。

这是我打算抓取的页面的 HTML 布局示例。红色框标出所需数据。

这是我在学习了一些教程后编写的代码。

<?php
include "simple_html_dom.php";
// Create DOM from URL
$html = file_get_html('http://www.freelancer.com/jobs/Website-Design/1/');

//Get all data inside the <tr> of <table id="project_table">
foreach($html->find('table[id=project_table] tr') as $tr) {

    foreach($tr->find('td[class=title-col]') as $t) {
        //get the inner HTML
        $data = $t->outertext;
        echo $data;
    }
}

?>

希望有人可以为我指明正确的方向,让我知道如何让它发挥作用。

谢谢。

【问题讨论】:

  • 查看原始源代码ctrl+u,数据在table[id=project_table_static]
  • project_table_static 不起作用。

标签: php parsing simple-html-dom


【解决方案1】:

原始源代码不同,这就是您没有得到预期结果的原因...

您可以使用ctrl+u查看原始源代码,数据在table[id=project_table_static]中,而单元格td没有属性,因此,这是一个从表中获取所有URL的工作代码:

$url = 'http://www.freelancer.com/jobs/Website-Design/1/';
// Create DOM from URL
$html = file_get_html($url);

//Get all data inside the <tr> of <table id="project_table">
foreach($html->find('table#project_table_static tbody tr') as $i=>$tr) {

    // Skip the first empty element
    if ($i==0) {
        continue;
    }

    echo "<br/>\$i=".$i;

    // get the first anchor
    $anchor = $tr->find('a', 0);
    echo " => ".$anchor->href;
}

// Clear dom object
$html->clear(); 
unset($html);

Demo

【讨论】:

    猜你喜欢
    • 2016-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-12
    相关资源
    最近更新 更多