You need to enable JavaScript to run this app. 使用Python requests与BeautifulSoup实现多入口链接全分页标题抓取
优惠活动
大模型
产品
解决方案
定价
更多

使用Python requests与BeautifulSoup实现多入口链接全分页标题抓取

多页遍历逻辑整合实现

核心整合逻辑

现有代码的爬取链路为「主站提取12个入口→遍历入口单页→提取单页标题」,只需要在入口遍历的内层增加分页循环分支:对每个入口链接,从第一页开始完成标题提取后,自动定位当前页的下一跳分页地址,拼接为可访问的绝对链接后重复请求、提取标题的流程,直到无有效下一页时再切换到下一个入口链接,即可覆盖全部分页内容。

原有代码需修正的问题

  • 原分页提取逻辑存在硬编码索引、API使用错误的问题:

    原代码soup.find('ul', {'class' : 'pagination'}).select('li', {'class': "page-link"})[2].find('a')['href']中,BeautifulSoup的select()方法第二个参数不支持传入属性筛选字典,且硬取索引位的方式会在最后一页(无下一页按钮)时触发越界报错。

  • 全局标题列表如果在循环内反复重置,会覆盖之前存储的爬取结果,需要初始化在循环外层。
  • 手动拼接链接的方式容易出现路径错误,建议使用urllib.parse.urljoin()处理相对路径拼接,避免地址失效。

整合后的可运行代码

import time
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin

# 全局存储所有爬取到的新闻标题
title_news = []
base_site = 'http://mlg.ucd.ie/modules/COMP41680/assignment2/'

# 第一步:从主站提取12个入口链接(优化原有链接拼接逻辑)
index_url = urljoin(base_site, 'index.html')
res = requests.get(index_url)
soup = BeautifulSoup(res.text, 'html.parser')
all_urls = []
for link in soup.find_all("a")[1:]:
    link_address = urljoin(base_site, link.get("href"))
    all_urls.append(link_address)

# 第二步:遍历每个入口链接,内层增加分页循环
for entry_url in all_urls:
    current_page_url = entry_url
    # 分页循环:只要存在有效当前页地址就持续爬取
    while current_page_url:
        res = requests.get(current_page_url)
        soup = BeautifulSoup(res.text, 'html.parser')
        
        # 提取当前页所有新闻标题
        news_div = soup.find_all('div', class_ = 'article')    
        for container in news_div:
            title = container.h5.a.text.strip()
            title_news.append(title)
        
        # 定位下一页链接,替换原有硬编码的分页提取逻辑
        current_page_url = None
        try:
            # 从分页组件中找文本为"Next"的下一页按钮
            next_page_btn = soup.find('ul', class_='pagination').find('a', string=lambda t: t and 'Next' in t.strip())
            if next_page_btn:
                next_page_path = next_page_btn['href']
                # 拼接为绝对地址,进入下一轮分页
                current_page_url = urljoin(base_site, next_page_path)
        except AttributeError:
            # 页面无分页组件时,直接跳出当前入口的分页循环
            current_page_url = None
        
        # 简单延时,避免高频请求给站点造成压力
        time.sleep(0.5)

# 爬取完成后可打印验证结果
print(f"共爬取到{len(title_news)}条新闻标题")

关键实现说明

  • 分页循环的退出条件完全由页面实际的分页组件决定,不硬编码总页数,适配不同入口下的分页数量差异。
  • 下一页按钮的定位替换原有索引取值方式,直接匹配“Next”文本,不会因为分页序号的变化导致定位失效。
  • 增加异常捕获逻辑,在页面不存在分页节点时自动终止当前入口的爬取流程,避免程序直接崩溃。

内容的提问来源于stack exchange,提问作者Negin Zarbakhsh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.27 00:36:08