PHP简单爬虫怎么写

wen PHP项目 4

本文目录导读:

PHP简单爬虫怎么写

  1. 基础版 - 使用file_get_contents
  2. 进阶版 - 使用cURL(推荐)
  3. 实用版 - 抓取并解析网页内容
  4. 使用PHP内置库(DOMDocument)
  5. 完整的爬虫示例(抓取文章列表)
  6. 注意事项:
  7. 常用技巧:

我来教你写一个简单的PHP爬虫,这里提供几个不同层次的示例:

基础版 - 使用file_get_contents

<?php
// 简单的页面抓取
$url = 'https://example.com';
$html = file_get_contents($url);
// 输出抓取的内容
echo $html;
?>

进阶版 - 使用cURL(推荐)

<?php
function getPageContent($url) {
    // 初始化cURL
    $ch = curl_init();
    // 设置cURL选项
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过SSL验证
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);   // 跟随重定向
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');
    // 执行请求
    $content = curl_exec($ch);
    // 检查错误
    if (curl_errno($ch)) {
        echo 'Error: ' . curl_error($ch);
        curl_close($ch);
        return false;
    }
    // 关闭cURL
    curl_close($ch);
    return $content;
}
// 使用示例
$url = 'https://example.com';
$content = getPageContent($url);
echo $content;
?>

实用版 - 抓取并解析网页内容

<?php
class SimpleCrawler {
    private $url;
    private $html;
    public function __construct($url) {
        $this->url = $url;
        $this->fetchContent();
    }
    // 抓取网页内容
    private function fetchContent() {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
        $this->html = curl_exec($ch);
        curl_close($ch);
    }
    // 提取标题
    public function getTitle() {
        preg_match('/<title>(.*?)<\/title>/i', $this->html, $matches);
        return isset($matches[1]) ? $matches[1] : null;
    }
    // 提取所有链接
    public function getLinks() {
        preg_match_all('/<a[^>]+href=["\']([^"\']+)["\']/i', $this->html, $matches);
        return isset($matches[1]) ? $matches[1] : [];
    }
    // 提取图片URL
    public function getImages() {
        preg_match_all('/<img[^>]+src=["\']([^"\']+)["\']/i', $this->html, $matches);
        return isset($matches[1]) ? $matches[1] : [];
    }
    // 提取所有文字(去除HTML标签)
    public function getText() {
        $text = strip_tags($this->html);
        return trim(preg_replace('/\s+/', ' ', $text));
    }
    // 提取特定类名的元素内容
    public function getElementsByClass($class) {
        $pattern = '/<[^>]*class=["\'][^"\']*' . preg_quote($class) . '[^"\']*["\'][^>]*>(.*?)<\/[^>]+>/i';
        preg_match_all($pattern, $this->html, $matches);
        return isset($matches[1]) ? $matches[1] : [];
    }
}
// 使用示例
$crawler = new SimpleCrawler('https://example.com');
echo "网页标题: " . $crawler->getTitle() . "\n";
echo "所有链接: \n";
print_r($crawler->getLinks());
echo "所有图片: \n";
print_r($crawler->getImages());
echo "网页文字: " . substr($crawler->getText(), 0, 200) . "...\n";
?>

使用PHP内置库(DOMDocument)

<?php
function parseHTML($html) {
    $dom = new DOMDocument();
    // 抑制警告,处理HTML5标签
    libxml_use_internal_errors(true);
    @$dom->loadHTML($html);
    libxml_clear_errors();
    return $dom;
}
// 使用DOMDocument提取内容
function getContentByXPath($html, $xpath) {
    $dom = parseHTML($html);
    $xpathObj = new DOMXPath($dom);
    $elements = $xpathObj->query($xpath);
    $results = [];
    foreach ($elements as $element) {
        $results[] = $element->textContent;
    }
    return $results;
}
// 示例:获取所有h1标签内容
$url = 'https://example.com';
$html = file_get_contents($url);
$h1Contents = getContentByXPath($html, '//h1');
print_r($h1Contents);
?>

完整的爬虫示例(抓取文章列表)

<?php
class ArticleCrawler {
    private $baseUrl;
    private $results = [];
    public function __construct($baseUrl) {
        $this->baseUrl = $baseUrl;
    }
    // 主爬取方法
    public function crawl($category) {
        $url = $this->baseUrl . '/' . $category;
        $html = $this->fetchContent($url);
        if (!$html) {
            return false;
        }
        // 解析文章列表
        preg_match_all('/<article.*?<h2><a[^>]+href=["\']([^"\']+)["\'][^>]*>(.*?)<\/a>/s', $html, $matches);
        for ($i = 0; $i < count($matches[1]); $i++) {
            $this->results[] = [
                'title' => trim(strip_tags($matches[2][$i])),
                'url' => $matches[1][$i],
                'fetched_at' => date('Y-m-d H:i:s')
            ];
        }
        return $this->results;
    }
    private function fetchContent($url) {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; MyCrawler/1.0)',
            CURLOPT_CONNECTTIMEOUT => 10,
            CURLOPT_TIMEOUT => 30
        ]);
        $content = curl_exec($ch);
        curl_close($ch);
        return $content;
    }
    public function saveToCSV($filename) {
        $fp = fopen($filename, 'w');
        // 写入表头
        fputcsv($fp, ['标题', 'URL', '抓取时间']);
        // 写入数据
        foreach ($this->results as $row) {
            fputcsv($fp, $row);
        }
        fclose($fp);
        echo "数据已保存到: $filename\n";
    }
}
// 使用方法
$crawler = new ArticleCrawler('https://example.com');
$articles = $crawler->crawl('news');
if ($articles) {
    $crawler->saveToCSV('articles.csv');
    echo "共抓取 " . count($articles) . " 篇文章\n";
}
?>

注意事项:

  1. 遵守robots.txt:在爬取前检查网站的robots.txt文件
  2. 设置请求间隔:避免对目标服务器造成压力
  3. 身份伪装:设置合理的User-Agent
  4. 错误处理:添加超时和错误处理机制
  5. 数据存储:将抓取的数据适当存储(数据库、文件等)
  6. 法律合规:确保爬取行为符合网站条款和相关法律法规

常用技巧:

// 设置cookie
curl_setopt($ch, CURLOPT_COOKIE, 'name=value; name2=value2');
// 模拟表单提交(POST)
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
// 处理编码问题
$content = mb_convert_encoding($content, 'UTF-8', 'GBK');
// 延迟请求(避免被封IP)
sleep(rand(1, 3));

示例涵盖了常见的PHP爬虫实现方式,从简单到复杂,你可以根据实际需求选择使用,记住要合理使用爬虫,尊重网站的规定。

抱歉,评论功能暂时关闭!