You need to enable JavaScript to run this app. 使用BeautifulSoup批量爬取时部分页面属性缺失如何添加条件判断
优惠活动
大模型
产品
解决方案
定价
更多

使用BeautifulSoup批量爬取时部分页面属性缺失如何添加条件判断

报错核心原因

当前脚本运行中断主要来自两类空值/越界错误:

  • 调用find()匹配不到目标节点时会返回None,后续直接链式获取子元素(比如headers_containers.h2.text)会触发AttributeError
  • 调用find_all()返回的列表长度不足时,直接按固定索引7取值会触发IndexError

只要在每一层节点取值时增加存在性判断,字段缺失时追加统一占位值(一般为空字符串),就能实现无中断的批量爬取,同时要注意每爬取一个URL,所有目标列表都必须同步追加元素,保证各列表长度和爬取条目数对齐,避免后续数据整理时列错位。

改造后的兼容版循环代码

for u in urllist:
    # 先处理请求异常场景,单URL请求失败不中断全局循环
    try:
        response = get(u, timeout=10)
        response.raise_for_status()
        html_soup = BeautifulSoup(response.text, "html.parser")
    except Exception:
        # 请求失败时所有字段统一补占位值
        name.append("")
        year.append("")
        country.append("")
        population.append("")
        taps.append("")
        toiletsToPerson.append("")
        continue

    # 提取聚居地名称
    headers_containers = html_soup.find('div', class_ = 'settlement-base-status section text-center')
    if headers_containers and headers_containers.h2:
        names = headers_containers.h2.text.strip()
    else:
        names = ""
    name.append(names)

    # 提取聚居地建立年份
    if headers_containers and headers_containers.h3:
        year_established = headers_containers.h3.text.strip()
    else:
        year_established = ""
    year.append(year_established)

    # 提取所属国家
    headers1_containers = html_soup.find('div', class_ = 'col-xs-12 text-center')
    if headers1_containers and headers1_containers.h4 and headers1_containers.h4.a:
        countries = headers1_containers.h4.a.text.strip()
    else:
        countries = ""
    country.append(countries)

    # 提取人口数据
    headers2_containers = html_soup.find('div', class_ = 'bold-it', id = "population")
    if headers2_containers:
        populations = headers2_containers.text.strip()
    else:
        populations = ""
    population.append(populations)

    # 提取公共水龙头数量
    headers3_containers = html_soup.find('div', class_ ='bold-it', id='sharedTaps')
    if headers3_containers:
        tap = headers3_containers.text.strip()
    else:
        tap = ""
    taps.append(tap)

    # 提取厕位人口配比
    headers4_containers = html_soup.find_all('div', class_ = 'bold-it')
    # 列表长度够长才取索引7的元素,避免越界
    if len(headers4_containers) >= 8:
        toiletSeat_toPerson = headers4_containers[7].text.strip()
    else:
        toiletSeat_toPerson = ""
    toiletsToPerson.append(toiletSeat_toPerson)

额外说明

  • 所有判断都做了多层嵌套校验,不会出现“外层节点存在但内层子元素缺失”导致的空值报错
  • 文本提取环节加了strip()清理首尾换行、多余空格,减少脏数据
  • 加了10秒请求超时设置,避免单个无响应URL卡住整个爬取流程

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.28 15:36:03