【问题标题】:using query in DOMXpath wont work if class name contains white space如果类名包含空格,则在 DOMXpath 中使用查询将不起作用
【发布时间】:2014-07-19 00:12:00
【问题描述】:

我正在尝试使用 php bot 从外部站点提取链接。链接在里面

<td class=" title-col"> <a href="http://examplenews101.com/post1">News 1</a> </td>

注意“title-col”之前有一个空格。

这是我使用的无法提取链接的脚本

function crawl_page($url, $depth = 5)   {
static $seen = array();
if (isset($seen[$url]) || $depth === 0) {
    return;
}

$seen[$url] = true;

$dom = new DOMDocument('1.0');
//als tried true , but no change in results
$dom->preserveWhiteSpace = false;
@$dom->loadHTMLFile($url);
$xpath = new DOMXpath($dom);
$td = $xpath->query('//td[contains(concat(" ", normalize-space(@class), " "), "title-col")]');
// also tried this, but not working
//$td = $xpath->query('//td[contains(@class,"title-col")]');

//I only get values when I use this
//$td = $dom->getElementsByTagName('td');

foreach( $td as $t )  {
    $anchors  = $t->getElementsByTagName('a'); 
    foreach ($anchors  as $element) {
        $href = $element->getAttribute('href');
        if (0 !== strpos($href, 'http')) {
            $path = '/' . ltrim($href, '/');
            if (extension_loaded('http')) {
            $href = http_build_url($url, array('path' => $path));
            } 
            else {
                $parts = parse_url($url);
                $href = $parts['scheme'] . '://';
                if (isset($parts['user']) && isset($parts['pass'])) {
                    $href .= $parts['user'] . ':' . $parts['pass'] . '@';
                }
                $href .= $parts['host'];
                if (isset($parts['port'])) {
                    $href .= ':' . $parts['port'];
                }
                $href .= $path;
            }
        }
        crawl_page($href, $depth - 1);
   }
}

echo "URL:" . $url . "<br/>";

}

我只有在使用这个时才会得到值

$td = $dom->getElementsByTagName('td');

但我需要按类查询。

谢谢

【问题讨论】:

    标签: javascript domdocument domxpath


    【解决方案1】:

    我发现这是由于 javascript 生成的属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-06
      • 1970-01-01
      • 2013-11-15
      • 2014-05-26
      相关资源
      最近更新 更多