You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用BeautifulSoup批量爬取网站超过8个就崩溃怎么解决?

问题根因

程序崩溃和内存、处理站点数量没有关联,是因为没有做异常捕获,单个请求、解析环节出错就会终止整个程序,刚好预置的站点列表里第N个请求触发了错误,才会出现“超过8个就崩溃”的错觉,具体错误点如下:

  • 反爬拦截:大部分正规站点会校验请求头,不带User-Agent的爬虫请求大概率会被拦截返回403/404/503等错误,requests.get收到非200状态码不会自动处理,直接抛出异常终止程序。
  • 解析容错缺失:部分站点不存在title标签,soup.find('title')返回None时直接调用.get_text()会触发AttributeError直接崩溃。
  • 网络异常未处理:请求可能出现超时、DNS解析失败、连接重置等各类网络问题,没有异常捕获的情况下任何一个问题都会直接终止程序。

修复后可直接运行的代码

import requests
from bs4 import BeautifulSoup

# 伪装浏览器请求头,避免被基础反爬拦截
HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
}

lst = ['https://covid19tracker.ca/provincevac.html?p=ON', 'https://www.ontario.ca/page/reopening-ontario#foot-1', 'https://blog.twitter.com/en_us/topics/company/2020/keeping-our-employees-and-partners-safe-during-coronavirus.html', 'https://www.aboutamazon.com/news/company-news/amazons-covid-19-blog-updates-on-how-were-responding-to-the-crisis#covid-latest', 'https://www.bcg.com/en-us/publications/2021/advantages-of-remote-work-flexibility', 'https://news.prudential.com/increasingly-workers-expect-pandemic-workplace-adaptations-to-stick.htm', 'https://www.mckinsey.com/featured-insights/future-of-work/whats-next-for-remote-work-an-analysis-of-2000-tasks-800-jobs-and-nine-countries', 'https://www.gsb.stanford.edu/faculty-research/publications/does-working-home-work-evidence-chinese-experiment', 'https://www.livecareer.com/resources/careers/planning/is-remote-work-here-to-stay']

for url in lst:
    try:
        # 加请求头、加状态码校验
        resp = requests.get(url, headers=HEADERS, timeout=10)
        resp.raise_for_status() # 非200状态码直接抛出异常进入except分支
        cite = resp.content
        soup = BeautifulSoup(cite, 'html.parser')
        title_tag = soup.find('title')
        # 处理title不存在的情况
        title = title_tag.get_text().strip() if title_tag else '无title标签'
        print(title)
    except Exception as e:
        # 单个站点出错仅打印提示,不中断整个循环
        print(f"站点{url}处理失败,错误信息:{str(e)}")

print("Didn't crash")

核心修改说明

  • 新增浏览器UA请求头,规避大部分基础反爬拦截
  • 所有单站点的请求、解析逻辑都放在try-except块内,单个站点出错只会跳过不会终止整个程序
  • 新增状态码校验resp.raise_for_status(),主动识别请求失败的情况
  • 新增title标签存在性判断,避免解析空值时报错
  • 优化循环写法,不需要通过索引遍历列表,直接迭代列表元素即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 01:06:05