You need to enable JavaScript to run this app. Python使用BeautifulSoup提取第二个a标签链接的实现方法
优惠活动
大模型
产品
解决方案
定价
更多

Python使用BeautifulSoup提取第二个a标签链接的实现方法

提取指定分页模块内第二个<a>标签href的实现方法
  • 前置环境准备
    先安装核心依赖库,在终端执行命令:pip install beautifulsoup4
  • 完整实现代码
    from bs4 import BeautifulSoup
    
    # 替换为你实际获取到的目标HTML片段
    target_html = '''
    <div class="archive-pagination pagination">
    <ul>
    <li class="active" >
    <a href="https://random.com/" aria-label="Current page" aria-current="page">1</a>
    </li>
    <li>
    <a href="https://google.com/">2</a>
    </li>
    </ul>
    </div>
    '''
    
    # 初始化解析对象,使用Python内置html.parser无需额外安装依赖
    soup = BeautifulSoup(target_html, 'html.parser')
    
    # 先定位分页模块容器,缩小匹配范围
    pagination_block = soup.find('div', class_='archive-pagination pagination')
    # 获取容器下所有a标签
    a_tag_list = pagination_block.find_all('a')
    # 取列表索引1的元素(对应第二个a标签),提取href属性
    second_link = a_tag_list[1]['href']
    
    print(second_link)
    # 运行后输出:https://google.com/
    
  • 实用注意事项
    • 不要直接全局搜索整个HTML文档的第二个a标签:如果页面其他位置存在a标签,会直接导致提取值错误,必须先锁定对应的分页容器节点范围
    • 索引规则注意:find_all返回的列表从0开始计数,第二个元素对应索引1,误用索引2会触发列表越界报错
    • 抗结构变动优化:如果担心分页模块后续调整a标签顺序,可以换用文本匹配的方式定位目标链接,写法为pagination_block.find('a', string='2')['href'],这种方式不受元素顺序变化的影响,稳定性更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.02 12:36:09