duanji5569 2014-07-03 22:35
浏览 63

DOMXPath返回零

Im trying to extract some information from a website. The info I need is contained in a table, I have already created a query to find it. When using the console from Chrome I can see the table I need is returned by the expression. But when I set up the PHP code, the query returns zero.

This is from the Chrome console

enter image description here

And this is my PHP code

$ch = curl_init($domain);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$cl = curl_exec($ch);
$dom = new DOMDocument();
@$dom->loadHTML($cl);
$xpath = new DOMXPath($dom);

$table = $xpath->query("//div[@id='content_fmainplace']//form/table/tbody/tr[15]//table");
echo $table->length;

Any ideas? What am I missing here?

  • 写回答

1条回答 默认 最新

  • dskld5423 2014-07-04 14:44
    关注

    You really dont need to target the div. Just target the id of the table instead. Consider this example: Sample Output

    $domain = 'http://app.cfe.gob.mx/Aplicaciones/CCFE/Tarifas/Tarifas/tarifas_casa.asp?Tarifa=DACTAR1E&Temporada4=Verano&Anio=2014&imprime=&Periodo=4&mes2=a+septiembre.&mes=1';
    $ch = curl_init($domain);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
    $cl = curl_exec($ch);
    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML($cl);
    libxml_clear_errors();
    $xpath = new DOMXPath($dom);
    
    // target the title
    $title = $values = $xpath->query('//table[@id="Table1"]/tr[1]/td[1]/form/table/tr[14]')->item(0)->nodeValue; // title rows
    $rows = $xpath->query('//table[@id="Table1"]/tr[1]/td[1]/form/table/tr[15]/td/table/tr');
    $row_values = array();
    
    // process td elements
    foreach($rows as $index => $row) {
        foreach($row->childNodes as $td) {
            // clean up
            $row_values[$index][] = preg_replace( '/\s+/', '', trim($td->nodeValue));
        }
        // clean up again
        $row_values[$index] = array_filter($row_values[$index]);
    }    
    
    ?>
    
    <!-- print them -->
    <h1><?php echo $title; ?></h1>
    <table cellpadding="10">
    <?php foreach($row_values as $values): ?>
        <tr><?php foreach($values as $value): ?>
            <td><?php echo $value; ?></td>
        <?php endforeach; ?></tr>
    <?php endforeach; ?>
    </table>
    
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!