【问题标题】:Retrieving categories from a website with DOMDocument and DOMXPath classes使用 DOMDocument 和 DOMXPath 类从网站检索类别
【发布时间】:2014-08-27 01:18:23
【问题描述】:

我有一个 PHP 代码可以使用“子标题”类名从该网站检索类别。但是,输出什么也不显示。我究竟做错了什么?

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;

}

?>

期望的输出:
农业
食品和饮料
服装
等等。

谢谢!

【问题讨论】:

  • @Ghost 谢谢!很好的帮助

标签: php html xpath web-scraping domdocument


【解决方案1】:

只针对特定元素。顺便说一句,您当前的代码在$grep&gt;loadHTMLFile 上有错字。 -&gt; 中缺少 -。我稍微修改了一下。

$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;
}

【讨论】:

  • 当然人很乐意提供帮助,顺便说一下,本教程可能会帮助您处理这种情况,这里有一些 notes
  • 谢谢 :) 我会记住的。这个网站抓取的东西让我头疼。
【解决方案2】:

要在使用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";
}

【讨论】:

    猜你喜欢
    • 2014-10-31
    • 2013-04-09
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    • 2016-11-11
    • 1970-01-01
    • 2012-09-14
    • 2022-08-03
    相关资源
    最近更新 更多