在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. Daniel Kim Daniel Kim

      What I appreciate most about this article is that it focuses on sustainable development practices. Anyone can write a script that scrapes one page. Writing a system that scrapes thousands of pages reliably day after day requires frameworks and proper architecture. This is the right way to think.

    2. 张伟 张伟

      一直在找这样的PHP爬虫解决方案。传统的curl方式处理并发太麻烦,自己实现队列又容易出bug。框架把这些都封装好了,开箱即用。Yurun Crawler基于Swoole的架构,并发性能应该很有保障。感谢分享!

    3. Michelle Lee Michelle Lee

      The framework approach forces you to think about your scraping project as a system, not a script. You consider error handling, logging, monitoring from day one. This article does a good job introducing that mindset shift, which is ultimately more valuable than any specific code example.

    4. 陈建国 陈建国

      之前用Python写爬虫,虽然库多但团队维护成本高。看到PHP生态也有这样的框架,而且基于Swoole性能应该不差,很心动。特别是注解方式定义字段,代码整洁度远超预期。准备在下一个项目试点使用。

    5. Robert Taylor Robert Taylor

      For teams already deep in the PHP ecosystem, having robust crawling frameworks is a huge productivity boost. No need to maintain a separate Python service just for scraping. Everything stays in one language, one codebase. This article makes a compelling case for that approach.

    6. Natalie Wong Natalie Wong

      The annotation-based approach reminds me of how ORMs work - declarative and clean. Instead of procedural extraction code scattered everywhere, you have clear, readable definitions of what data you want and where to find it. This is how professional code should look.

    7. 林小夕 林小夕

      PHP爬虫框架这个概念确实打开了新世界的大门。以前总觉得爬虫就是写循环发请求然后正则匹配,代码越写越乱。看到框架带来的结构和可维护性,决定彻底改变自己的开发方式。期待更多这样的深度文章!

    8. Chris Evans Chris Evans

      This is the kind of practical, architectural advice that's hard to find in tutorials. Most content just shows you how to scrape a single page with basic curl. But real-world scraping needs frameworks, queues, error handling - this article points developers in the right direction.

    9. 吴军 吴军

      做采集最头疼的就是目标网站改版,之前写的解析代码全废。文章里提到的注解方式定义字段映射,简直就是救星!规则和代码分离,维护成本直线下降。已经在研究Yurun Crawler的文档了,感谢推荐!

    10. 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.

    11. 张小凡 张小凡

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