最近闲来无事,有个朋友问我他在用PHP写一个抓取图书信息的爬虫程序出现了一些BUG,想要让我看下帮他修改,无奈写的语法太过复杂凌乱,索性我重头再来,直接用自己的方式写了一篇给他一些思路做参考。
以下是一个使用PHP编写的简单图书信息爬虫示例,使用 GuzzleHttp
发送HTTP请求和 Symfony DomCrawler
解析HTML内容:
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
use Symfony\Component\DomCrawler\Crawler;
// 创建HTTP客户端
$client = new Client([
'headers' => [
'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
]
]);
// 存储结果的CSV文件
$csvFile = fopen('books.csv', 'w');
fputcsv($csvFile, ['书名', '作者', '价格', '评分', '简介']);
// 示例:爬取豆瓣读书的编程类书籍(实际使用时请遵守网站规则)
$baseUrl = 'https://book.douban.com/tag/编程?start=%d';
for ($page = 0; $page < 3; $page += 20) { // 爬取3页
try {
$response = $client->get(sprintf($baseUrl, $page));
$html = (string)$response->getBody();
$crawler = new Crawler($html);
// 提取图书信息
$crawler->filter('li.subject-item')->each(function (Crawler $node) use ($csvFile) {
$title = $node->filter('h2 a')->text();
$info = $node->filter('.pub')->text();
$rating = $node->filter('.rating_nums')->text('暂无评分');
$desc = $node->filter('.info p')->text('暂无简介');
// 清理数据
$info = trim(str_replace(["\n", " "], "", $info));
list($author, $publisher, $price) = explode('/', $info, 3) + ['', '', ''];
fputcsv($csvFile, [
trim($title),
trim($author),
trim($price),
trim($rating),
trim($desc)
]);
});
echo "已抓取第 ".($page/20+1)." 页数据\n";
sleep(1); // 遵守爬虫道德,添加延迟
} catch (Exception $e) {
echo "抓取失败: ".$e->getMessage()."\n";
}
}
fclose($csvFile);
echo "数据已保存到 books.csv\n";
robots.txt
规则// 随机延迟
sleep(rand(1, 3));
// 使用代理
$client = new Client([
'proxy' => 'http://user:pass@proxy:port'
]);
// 使用PDO存储到MySQL
$pdo = new PDO('mysql:host=localhost;dbname=books', 'user', 'pass');
$stmt = $pdo->prepare("INSERT INTO books (...) VALUES (...)");
$stmt->execute([...]);
// 使用Guzzle的异步并发
$promises = [];
foreach ($urls as $url) {
$promises[] = $client->getAsync($url);
}
$results = GuzzleHttp\Promise\unwrap($promises);
上面就是我所编写的全部过程,不过如果有更好的方案或者建议可以评论区留言讨论。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有