php实现爬虫
PHP实现爬虫的方法
使用file_get_contents或cURL获取网页内容
通过file_get_contents函数可以简单获取网页内容,但灵活性较低。更推荐使用cURL库,支持更多高级功能如设置请求头、处理Cookie等。
$url = 'https://example.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$html = curl_exec($ch);
curl_close($ch);
使用DOMDocument解析HTML
获取网页内容后,可以使用PHP内置的DOMDocument类来解析HTML并提取所需数据。
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$titles = $xpath->query('//h1');
foreach ($titles as $title) {
echo $title->nodeValue . "\n";
}
处理JavaScript渲染的页面
对于动态加载内容的页面,可以使用无头浏览器如Puppeteer配合PHP的exec函数,或直接使用PHP的无头浏览器库如PHP-FX。
// 需要安装Node.js和Puppeteer
exec('node puppeteer_script.js', $output);
$html = implode("\n", $output);
处理反爬机制
设置合理的User-Agent和请求间隔可以避免被目标网站封禁。使用代理IP池和随机延迟也是常见策略。
$userAgents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)'
];
curl_setopt($ch, CURLOPT_USERAGENT, $userAgents[array_rand($userAgents)]);
sleep(rand(1, 3)); // 随机延迟
存储爬取的数据
将爬取到的数据存储到数据库或文件中,便于后续处理和分析。
$data = ['title' => 'Example', 'content' => '...'];
file_put_contents('data.json', json_encode($data));
// 或存入数据库
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$stmt = $pdo->prepare('INSERT INTO pages (title, content) VALUES (?, ?)');
$stmt->execute([$data['title'], $data['content']]);
使用现成的爬虫框架
对于复杂项目,可以考虑使用现成的PHP爬虫框架如Goutte(基于Symfony组件)或Spider。
require 'vendor/autoload.php';
$client = new Goutte\Client();
$crawler = $client->request('GET', 'https://example.com');
$crawler->filter('h1')->each(function ($node) {
echo $node->text() . "\n";
});
遵守robots.txt和法律法规
在开发爬虫时务必检查目标网站的robots.txt文件,遵守其中的规则。同时确保爬虫行为符合当地法律法规,避免对目标网站造成过大负载。







