在PHP中,通过“框架的方式”浏览网页并获取指定内容


一、使用专业的爬虫框架

对于大型或复杂的采集项目,使用完整的爬虫框架能大大提高开发效率和代码可维护性。

Yurun Crawler

这是一个基于 Swoole 的高性能、分布式爬虫框架。它的特点是低代码,甚至可以通过注解来定义如何从页面中提取数据:

<?php
use Yurun\Crawler\Module\Parser\Annotation\DomSelect;
use Yurun\Crawler\Module\Parser\Enum\DomSelectMethod;
use Yurun\Crawler\Module\DataModel\Contract\BaseDataModel;

class ArticleModel extends BaseDataModel
{
    /**
     * 标题
     * @DomSelect(selector=".article-view h1", method=DomSelectMethod::TEXT)
     */
    public $title;

    /**
     * 内容
     * @DomSelect(selector=".article-content", method=DomSelectMethod::HTML)
     */
    public $content;
}

Advance PHP Scraper

这是一个功能强大且模块化的库,对初学者非常友好。它提供了简单直接的API来提取链接、图片、元标签等,同时也支持限流、异步抓取和插件系统等高级特性。

PhpDig

这是一个经典的开源Web爬虫与搜索引擎系统,适合用于构建垂直领域的搜索引擎。


二、使用解析类库

如果不需要完整的框架,只想在现有项目中引入解析功能,使用轻量的HTML解析库会更方便。

Symfony DomCrawler

这是 Symfony 框架的一个组件,也是许多高级爬虫库的底层依赖。它提供流畅的API来遍历文档树,并用CSS选择器或XPath精确查找节点。

simplehtmldom

这是一个非常流行且易于上手的HTML解析库,允许你像使用jQuery一样用 find() 方法查找元素:

<?php
require_once 'vendor/autoload.php';
use simplehtmldom\HtmlWeb;

$web = new HtmlWeb();
$html = $web->load('https://example.com');

// 查找所有段落并输出其内容
$paragraphs = $html->find('p');
foreach ($paragraphs as $p) {
    echo $p->innertext . PHP_EOL;
}

Snoopy

这是一个经典的PHP类,主要用于模拟Web浏览器的功能,可以抓取网页内容、提交表单等。虽然它本身不是解析器,但常被用于第一步的"获取网页内容"。


三、使用PHP内置的DOM扩展

PHP内置的 DOMDocumentDOMXPath 类是非常强大的解析工具,不需要安装任何第三方库。它们提供了标准的DOM操作方式和XPath定位能力:

<?php
// 获取网页内容
$html = file_get_contents('https://example.com');

// 创建DOMDocument对象
$dom = new DOMDocument();
// 忽略HTML解析警告
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_clear_errors();

// 创建XPath对象
$xpath = new DOMXPath($dom);

// 使用XPath查询指定内容,例如获取所有h1标签
$headings = $xpath->query('//h1');
foreach ($headings as $heading) {
    echo $heading->textContent . PHP_EOL;
}

// 获取class为content的元素
$content = $xpath->query("//*[contains(@class, 'content')]")->item(0);
if ($content) {
    echo $content->textContent;
}

四、注意事项

  1. 遵守robots.txt:在采集网站前,请查看目标网站的 robots.txt 文件,尊重网站的爬取规则。
  2. 设置合理的请求间隔:避免对目标服务器造成过大压力,建议在请求之间添加适当延迟。
  3. 处理编码问题:确保正确处理网页的字符编码,避免中文乱码。
  4. 模拟浏览器User-Agent:有些网站会拦截非浏览器的请求,设置合理的User-Agent可以提高成功率。
  5. 处理动态内容:如果目标网页内容通过JavaScript动态加载,上述基于HTML解析的方案可能无法获取数据,此时需要使用无头浏览器(如Puppeteer、Selenium)配合PHP使用。

选择哪种方案取决于你的具体需求:如果是简单项目,建议使用 simplehtmldom 或内置的 DOMDocument;如果是大规模采集,可以考虑 Yurun Crawler 等专业框架。

已有 35 条评论

    1. Emma Thompson Emma Thompson

      The mention of distributed crawling capabilities is crucial for anyone working at scale. Being able to distribute the workload across multiple machines while maintaining a clean code structure is exactly what enterprise projects need. Great to see PHP frameworks addressing this.

    2. 张小凡 张小凡

      作为一个PHP新手,之前一直以为爬虫是Python的专利。看了这篇文章才知道PHP也能做得很优雅。框架的概念让代码结构清晰了很多,不像网上那些教程教的一堆面条式代码。准备按照这个思路开始我的第一个爬虫项目了。

    3. Kevin Lee Kevin Lee

      I've been using custom curl scripts for years and always dreaded maintenance. This article opened my eyes to how much time I've been wasting. The annotation approach in particular would save so much headache when sites update their HTML structure. Time to upgrade my workflow!

    4. Rachel Green Rachel Green

      The "framework way" isn't just about code structure - it's about adopting best practices that have been battle-tested by the community. Request throttling, retry mechanisms, proxy rotation - these are all things a good framework handles for you. This article does a great job introducing the concept.

    5. 王磊 王磊

      终于等到一篇讲PHP爬虫框架的文章了!之前用Python的Scrapy确实强大,但团队都是PHP背景,维护起来有难度。看到PHP也有这么成熟的方案,而且还能利用Swoole做高性能并发,这下可以统一技术栈了。感谢分享!