利用php和curl高效抓取新闻列表及详情
本文将详细讲解如何用php和curl高效抓取新闻列表和详情页内容。主要挑战在于:一、从列表页提取新闻标题和完整url;二、根据列表页url,进一步抓取详情页内容,最终整合标题、url和内容进行展示。
首先,解决从列表页获取新闻标题和完整url的问题。通过分析列表页源代码,我们可以利用正则表达式匹配标签中的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,然后使用正则表达式提取
<?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";
}
?>这段代码展示了如何使用curl和正则表达式完成新闻列表和详情的抓取。请根据实际网站结构调整正则表达式,并添加必要的错误处理和异常处理。 记住,在抓取数据时,务必遵守网站的robots.txt规则和相关法律法规。
以上就是如何用php高效采集新闻列表和详情?的详细内容,更多请关注代码网其它相关文章!
发表评论