利用php和curl高效抓取新闻列表及详情
本文将详细讲解如何用PHP和cURL高效抓取新闻列表和详情页内容。主要挑战在于:一、从列表页提取新闻标题和完整URL;二、根据列表页URL,进一步抓取详情页内容,最终整合标题、URL和内容进行展示。
首先,解决从列表页获取新闻标题和完整URL的问题。通过分析列表页源代码,我们可以利用正则表达式匹配<a></a>标签中的href属性和title属性(如果存在)来提取新闻标题和相对路径。由于提取的路径通常是相对路径,我们需要将其转换为完整URL。这需要在代码中添加网站根域名。

<?php
$url = 'http://www.xx.com/news'; // 列表页URL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_REFERER, '');
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// ... 其他cURL选项 ...
$html = curl_exec($ch);
curl_close($ch);
preg_match_all('/<a href="https://www.php.cn/link/01bebc8e971d09cb90cf5756b340f24c".*??>(.*?)/s', $html, $matches);
$newslist = [];
foreach ($matches[1] as $key => $relativepath) {
$completepath = $url . '/' . ltrim($relativepath, '/'); // 转换为完整URL
$newslist[] = [
'title' => $matches[2][$key],
'url' => $completepath,
];
}
// 现在 $newslist 数组包含标题和完整URL
var_dump($newslist);
?>接下来是第二个挑战:从详情页提取新闻内容。同样,我们使用cURL获取详情页HTML,然后使用正则表达式提取<div class="content text-xs">内的内容作为新闻内容。需要注意的是,正则表达式需要根据具体的详情页HTML结构进行调整。<p><span>立即学习</span>“<a href="https://pan.quark.cn/s/7fc7563c4182" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">PHP免费学习笔记(深入)</a>”;</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false;"><?php
foreach ($newslist as $news) {
$ch = curl_init($news['url']);
// ... 其他cURL选项 ...
$detailHtml = curl_exec($ch);
curl_close($ch);
preg_match('/<div class="content text-xs">(.*?)<\/div>/s', $detailHtml, $contentMatch);
$content = isset($contentMatch[1]) ? $contentMatch[1] : ''; // 处理无内容的情况
// 输出结果
echo "标题: " . $news['title'] . "\n";
echo "链接: " . $news['url'] . "\n";
echo "内容: " . $content . "\n\n";
}
?></pre>
以上就是如何用PHP高效采集新闻列表和详情?的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号