【问题标题】:simple crawler in php to echo linksphp中的简单爬虫来回显链接
【发布时间】:2011-07-06 01:21:37
【问题描述】:

我想用 php 制作一个简单的爬虫,它可以让我获取网页中的链接,回显它们的 url,然后爬到其他页面以在某个域下执行相同的操作。这里需要使用 cURL 吗?另外..如何指定爬虫的深度。

到目前为止我有这个:

    $dom = new DOMDocument;
$dom->loadHTML($html);
foreach( $dom->getElementsByTagName('a') as $node ) {
    echo $dom->saveXml($node), PHP_EOL;
}

【问题讨论】:

  • 如果唯一的问题是“使用或不使用 CURL” - 那么答案是“是的,使用它”
  • 好吧,我也想知道如何做到这一点...我对 cURL 还很陌生...而且我一直在环顾四周
  • 我想我会补充一点,您可能会遇到 PHP 超时限制

标签: php


【解决方案1】:

查看Snoopy,一个简单的 curl 包装器。下面是一些示例代码

/*
You need the snoopy.class.php from 
http://snoopy.sourceforge.net/
*/
 
include("snoopy.class.php");
 
$snoopy = new Snoopy;
 
// need an proxy?:
//$snoopy->proxy_host = "my.proxy.host";
//$snoopy->proxy_port = "8080";
 
// set browser and referer:
$snoopy->agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
$snoopy->referer = "http://www.jonasjohn.de/";
 
// set some cookies:
$snoopy->cookies["SessionID"] = '238472834723489';
$snoopy->cookies["favoriteColor"] = "blue";
 
// set an raw-header:
$snoopy->rawheaders["Pragma"] = "no-cache";
 
// set some internal variables:
$snoopy->maxredirs = 2;
$snoopy->offsiteok = false;
$snoopy->expandlinks = false;
 
// set username and password (optional)
//$snoopy->user = "joe";
//$snoopy->pass = "bloe";
 
// fetch the text of the website www.google.com:
if($snoopy->fetchtext("http://www.google.com")){ 
    // other methods: fetch, fetchform, fetchlinks, submittext and submitlinks
 
    // response code:
    print "response code: ".$snoopy->response_code."<br/>\n";
 
    // print the headers:
 
    print "<b>Headers:</b><br/>";
    while(list($key,$val) = each($snoopy->headers)){
        print $key.": ".$val."<br/>\n";
    }
 
    print "<br/>\n";
 
    // print the texts of the website:
    print "<pre>".htmlspecialchars($snoopy->results)."</pre>\n";
 
}
else {
    print "Snoopy: error while fetching document: ".$snoopy->error."\n";
}

您需要使用“fetchlinks”来获取链接。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-10
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    相关资源
    最近更新 更多