0


我用 PHP 编写了一些代码来从其他网站中提取某些元素的内容。这些元素由 XPath 处理。这些代码在一个网站上成功运行,但在另一个网站上却失败了。因此,我确信并非整个代码都不正确。
顺便说一句:我通过在 Firefox 中使用“检查元素”并右键单击该元素并选择“复制 XPath”来提取元素的 XPath 地址。

第二个网站有什么问题?

谢谢

这是代码:

//MyCode.PHP
<html>
<head>
<title>This is the title</title>
</head>
<body>

<?php 

class EmDIV
{
    public $url="";
    public $content="";
    public $name="";
    public $query="";
    public function EmDIV($CdivName,$Curl,$CQuery)
    {
        $this->name=$CdivName;
        $this->url=$Curl;
        $this->query=$CQuery;
        $html = new DOMDocument();
        @$html->loadHtmlFile($this->url);

        $bodies = $html->getElementsByTagName('body');
        assert($bodies->length === 1);
        $body = $bodies->item(0);
        $xpath = new DOMXPath( $html );
        $nodelist = $xpath->query($this->query);
        //echo @$body->saveHTML();
        if($nodelist->length==1)
        {
            $this->content=$nodelist->item(0)->textContent;
            //sanitizing
            //$this->content=Jsoup.clean($this->content, Whitelist.basic());
        }
        //echo $nodelist->item(0)->nodeName;        
        foreach ($nodelist as $node) 
            echo $node->getNodePath()."\n";     
    }
}

$emdiv=array(
//new EmDIV('parsmalaysia','http://www.parsmalaysia.com/exchange.html','/html/body/div/div[5]/div/div/div/div/div/div/div/div/div/div/table/tbody/tr/td[4]/text()'),
new EmDIV('atlas-exchange','http://atlas-exchange.com/','/html/body/div/div/table/tr/td/table/tr/td/div/div[10]/div/div/div/table/tr[3]/td[2]/text()'),
new EmDIV('usunmalaysia','http://www.usunmalaysia.com/Home.aspx','/html/body/form/table/tbody/tr[3]/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[4]/td/table/tbody/tr/td/table/tbody/tr/td[2]/div/table/tbody/tr[2]/td/table/tbody/tr/td/table/tbody/tr[2]/td/table/tbody/tr[3]/td/table/tbody/tr[4]/td[2]/text()'),
);
?>

<table border="1">
<tr>
<td>Site</td>
<td>RM Price</td>
</tr>
    <?php
        foreach ($emdiv as $ed) 
        {
            echo "<tr>";
            echo "<td>".$ed->name."</td>";
            echo "<td>".$ed->content."</td>";
            echo "</tr>";
        }
    ?>
</table> 

</body>
</html>
4

1 回答 1

0

在第二页中没有 tbody 元素。您必须从路径中删除所有 tbody 元素。Firefox 显示 tbody 元素,因为它们是表格内部结构的一部分,但它们不在您要检索的标记中。

于 2012-05-13T21:51:06.607 回答