【发布时间】:2011-06-11 08:28:16
【问题描述】:
如何使用 PHP 获取网页中的所有链接?
我需要获取链接列表:-
我想获取 href (http://www.google.com) 和 text (Google)
-------情况是:-
我正在构建一个爬虫,我希望它获取数据库表中存在的所有链接。
【问题讨论】:
如何使用 PHP 获取网页中的所有链接?
我需要获取链接列表:-
我想获取 href (http://www.google.com) 和 text (Google)
-------情况是:-
我正在构建一个爬虫,我希望它获取数据库表中存在的所有链接。
【问题讨论】:
有几种方法可以做到这一点,但我的处理方式类似于以下,
使用cURL获取页面,即:
// $target_url has the url to be fetched, ie: "http://www.website.com"
// $userAgent should be set to a friendly agent, sneaky but hey...
$userAgent = 'Googlebot/2.1 (http://www.googlebot.com/bot.html)';
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$html = curl_exec($ch);
if (!$html) {
echo "<br />cURL error number:" .curl_errno($ch);
echo "<br />cURL error:" . curl_error($ch);
exit;
}
如果一切顺利,页面内容现在都在 $html 中。
让我们继续并在 DOM 对象中加载页面:
$dom = new DOMDocument();
@$dom->loadHTML($html);
到目前为止一切顺利,XPath 可以从 DOM 对象中抓取链接:
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");
遍历结果并获取链接:
for ($i = 0; $i < $hrefs->length; $i++) {
$href = $hrefs->item($i);
$link = $href->getAttribute('href');
$text = $href->nodeValue
// Do what you want with the link, print it out:
echo $text , ' -> ' , $link;
// Or save this in an array for later processing..
$links[$i]['href'] = $link;
$links[$i]['text'] = $text;
}
$hrefs 是 DOMNodeList 类型的对象,并且 item() 返回指定索引的 DOMNode 对象。所以基本上我们有一个循环,将每个链接检索为一个 DOMNode 对象。
这应该可以为您完成。 我不能 100% 确定的唯一部分是链接是图像还是锚点,在这些情况下会发生什么,我不知道,因此您需要测试并过滤掉它们。
希望这能让您了解如何抓取链接,快乐编码。
【讨论】: