php 爬虫实现
PHP 爬虫实现方法
使用 cURL 获取网页内容
cURL 是 PHP 中用于发送 HTTP 请求的强大工具,可以模拟浏览器行为获取网页内容。
$url = "https://example.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
使用 file_get_contents 简单获取内容
对于简单的 HTTP 请求,可以使用 file_get_contents 函数,但功能较为有限。
$url = "https://example.com";
$content = file_get_contents($url);
echo $content;
解析 HTML 内容
使用 DOMDocument 或第三方库(如 PHP Simple HTML DOM Parser)解析 HTML 内容。
$dom = new DOMDocument();
@$dom->loadHTML($response);
$xpath = new DOMXPath($dom);
$elements = $xpath->query("//h1");
foreach ($elements as $element) {
echo $element->nodeValue . "\n";
}
处理 JavaScript 渲染的页面
对于动态加载的内容,可以使用无头浏览器工具如 Puppeteer 或通过 API 接口获取数据。
// 使用 Guzzle 调用 Puppeteer 后端服务
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'http://localhost:3000/scrape', [
'json' => ['url' => 'https://example.com']
]);
echo $response->getBody();
存储爬取的数据
将爬取的数据存储到数据库或文件中,便于后续处理。
$data = ["title" => "Example", "content" => "Sample content"];
file_put_contents('data.json', json_encode($data));
遵守 robots.txt 和法律法规
在开发爬虫时,务必遵守目标网站的 robots.txt 文件规定,避免频繁请求导致 IP 被封禁。
$robotsUrl = "https://example.com/robots.txt";
$robotsContent = file_get_contents($robotsUrl);
echo $robotsContent;
通过以上方法,可以实现基本的 PHP 爬虫功能,根据需求选择适合的工具和技术。







