🗣 Wd提问: php goutte
🤖 Ai回答: `Goutte` 是一个基于 PHP 的网页抓取(Web Scraping)库,它封装了 `Symfony BrowserKit`、`DomCrawler` 和 `GuzzleHttp`,提供了一个简单易用的 API 来模拟浏览器行为,抓取网页内容并解析 HTML。
✅ 安装 Goutte
使用 Composer 安装:
bash
composer require fabpot/goutte
注意:`fabpot/goutte` 是官方包,虽然作者 Fabien Potencier 已不再积极维护,但目前仍广泛使用且兼容主流 PHP 版本。
🧩 基本用法示例
1、抓取页面内容
php
<?php
require_once 'vendor/autoload.php';
use Goutte\Client;
$client = new Client();
// 发起 GET 请求
$crawler = $client-request('GET', 'https://65.hk');
// 获取页面标题
$title = $crawler-filter('title')-text();
echo Title: 、$title 、\n;
// 获取所有链接
$crawler-filter('a')-each(function ($node) {
echo $node-attr('href') 、\n;
});
2、表单提交(模拟登录等)
php
$crawler = $client-request('GET', 'https://65.hk/login');
// 填写表单并提交
$form = $crawler-selectButton('Login')-form();
$form['username'] = 'your_username';
$form['password'] = 'your_password';
$crawler = $client-submit($form);
// 检查是否登录成功
if ($crawler-filter('.welcome-message')-count() 0) {
echo 登录成功!\n;
}
3、使用 POST 请求
php
$crawler = $client-request('POST', 'https://65.hk/api', [
'param1' = 'value1',
'param2' = 'value2'
]);
🔍 DomCrawler 选择器语法
Goutte 使用 Symfony 的 `DomCrawler`,支持 CSS 选择器:
`id` —— 选择 ID
`.class` —— 选择类
`tag` —— 选择标签
`tag.class` —— 标签+类
`tag:nth-child(2)` —— 第二个子元素
php
$crawler-filter('div.content p')-each(function ($p) {
echo $p-text() 、\n;
});
⚠️ 注意事项
1、遵守 robots.txt 和网站条款
抓取前请确保你有权抓取该网站内容,避免法律风险。
2、设置 User-Agent
有些网站会屏蔽无 UA 的请求:
php
$client-setHeader('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)');
3、处理 JavaScript 渲染的页面
Goutte 不支持 JS 渲染,如需抓取动态内容,请改用 [Puppeteer](https://github.com/GoogleChrome/puppeteer) 或 [Selenium](https://www.selenium.dev/) + PHP WebDriver。
4、错误处理
php
try {
$crawler = $client-request('GET', 'https://65.hk');
} catch (\Exception $e) {
echo 请求失败: 、$e-getMessage();
}
🔄 替代方案(现代推荐)
如果你需要更强大或现代的功能:
| 需求 | 推荐工具 |
| 简单静态页面抓取 | ✅ Goutte(轻量、易用) |
| 动态页面(JS渲染) | 🌐 Puppeteer / Selenium |
| 高并发抓取 | 🚀 Guzzle + ReactPHP / Swoole |
| 更强的 DOM 解析 | 🧩 Symfony DomCrawler + custom HTTP client |
📚 参考文档
GitHub: https://github.com/FriendsOfPHP/Goutte
Symfony DomCrawler: https://symfony.com/doc/current/components/dom_crawler.html
✅ 总结:
Goutte 是 PHP 中抓取静态网页内容的最佳入门工具之一,适合快速开发爬虫、自动化测试、数据采集等场景。
如需进阶功能(如异步、JS 支持),可考虑结合其他工具或框架。
需要我帮你写一个完整的爬虫例子吗?比如抓取豆瓣电影 Top250?🎬
📣 商家广告:





0
IP地址: 202.185.67.36
搜索次数: 115
提问时间: 2025-11-07 01:50:08
本站所有
❓
问答
均由Ai自动分析整理,内容仅供参考,若有误差请用“联系”里面信息通知我们人工修改或删除。
本站由
🟢
豌豆Ai
提供技术支持,使用的最新版:
豌豆Ai站群搜索引擎系统 V.25.10.25
搭建本站。