繁体   English   中英

使用DOMDocument和DOMXPath类从网站中检索类别

[英]Retrieving categories from a website with DOMDocument and DOMXPath classes

我有一个PHP代码,可以使用类名“ sub-title”从此网站检索类别。 但是,输出不显示任何内容。 我究竟做错了什么?

PHP代码:

<?php
header('Content-Type: text/html; charset=utf-8');
$grep = new DoMDocument();
@$grep>loadHTMLFile("http://www.alibaba.com/Products",false,stream_context_create(array("http" => array("user_agent" => "any"))));

$finder = new DomXPath($grep);
$class = "sub-title";
$nodes = $finder->query("//*[contains(@class, '$class')]");

foreach ($nodes as $node) {
    $span = $node->childNodes;
    echo $span->item(0)->nodeValue;

}

?>

所需的输出:
农业
食品与饮料
服饰
等等..

谢谢!

仅针对该特定元素。 顺便说一下,您当前的代码在$grep>loadHTMLFile上有一个错字。 它遗漏--> 我做了一点修改。

$ch = curl_init('http://www.alibaba.com/Products');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
$html = curl_exec($ch);
$dom = new DOMDocument();
@$dom->loadHTML($html);
$finder = new DOMXPath($dom);
$nodes = $finder->query('//h4[@class="sub-title"]');

foreach ($nodes as $node) {
    $sub_title = trim(explode("\n", trim($node->nodeValue))[0]) . '<br/>';
    echo $sub_title;
}

要在使用DOMDocument::loadHTMLFile来获取HTML时设置流上下文,请使用libxml_set_streams_context

<?php

$context = stream_context_create(array('http' => array('user_agent' => 'any')));
libxml_set_streams_context($context);
libxml_use_internal_errors(true);

$doc = new DOMDocument();
$doc->loadHTMLFile('http://www.alibaba.com/Products');

$xpath = new DOMXPath($doc);
$nodes = $xpath->query('//h4[@class="sub-title"]/a');

foreach ($nodes as $node) {
    echo trim($node->textContent) . "\n";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM