
本文详解如何解决 beautifulsoup 爬虫常见失败原因:缺少请求头导致被拒绝、相对 url 无法正确跳转,并提供可直接运行的修复代码与最佳实践。
本文详解如何解决 beautifulsoup 爬虫常见失败原因:缺少请求头导致被拒绝、相对 url 无法正确跳转,并提供可直接运行的修复代码与最佳实践。
在使用 requests + BeautifulSoup 构建网页爬虫(例如课程目录抓取系统)时,初学者常遇到“返回空结果”或 AttributeError 等静默失败——表面代码无语法错误,实则因反爬机制或 URL 处理疏漏导致请求被拦截或解析中断。核心问题通常集中在两点:服务端拒绝无标识请求 和 相对路径未转为绝对路径。
以下是一个典型修复后的完整示例(以 Harvard Coursicle 课程页为例):
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
def scrape_course_catalog(base_url):
# ✅ 关键1:添加合法 User-Agent 请求头,模拟真实浏览器
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'
}
try:
response = requests.get(base_url, headers=headers, timeout=10)
response.raise_for_status() # 主动抛出 HTTP 错误(如 403/404)
except requests.exceptions.RequestException as e:
print(f"❌ 请求失败:{e}")
return []
soup = BeautifulSoup(response.content, "html.parser")
# ✅ 关键2:精准定位容器(注意原代码中拼写错误:'tileContaine' → 'tileContainer')
tile_container = soup.find("div", id="tileContainer")
if not tile_container:
print("⚠️ 未找到课程容器,请检查页面结构是否变更")
return []
courses = []
for link in tile_container.find_all("a", href=True):
# ✅ 关键3:将相对 href 转为绝对 URL,避免 404
absolute_url = urljoin(base_url, link["href"])
try:
detail_resp = requests.get(absolute_url, headers=headers, timeout=10)
detail_resp.raise_for_status()
detail_soup = BeautifulSoup(detail_resp.content, "html.parser")
# 示例:提取课程标题(根据实际页面结构调整选择器)
title_elem = detail_soup.find("h1") or detail_soup.find("title")
course_name = title_elem.get_text(strip=True) if title_elem else "未知课程"
courses.append({"name": course_name, "url": absolute_url})
except Exception as e:
print(f"⚠️ 解析课程页 {absolute_url} 失败:{e}")
continue
return courses
# 使用示例
if __name__ == "__main__":
url = "https://www.coursicle.com/harvard/courses/"
catalog = scrape_course_catalog(url)
print(f"✅ 成功获取 {len(catalog)} 门课程信息")
for item in catalog[:3]: # 仅打印前3条预览
print(f"- {item['name']} → {item['url']}")? 重要注意事项:
- 永远校验响应状态码:使用 response.raise_for_status() 及时捕获 403(禁止访问)、404(页面不存在)等异常;
- 警惕动态渲染内容:若目标页面依赖 JavaScript 渲染(如 React/Vue 应用),requests + BeautifulSoup 将无法获取真实 DOM,此时应改用 Selenium 或 Playwright;
- 遵守 robots.txt 与网站条款:爬取前请查阅 https://www.coursicle.com/robots.txt,并限制请求频率(建议添加 time.sleep(1));
- ID/Class 名易变:生产环境需加入容错逻辑(如多 selector 回退、日志记录结构变更),避免因前端微调导致整个爬虫崩溃。
通过以上三重加固(请求头伪装、URL 规范化、异常健壮处理),你的爬虫将显著提升稳定性与可维护性,真正迈向工程级数据采集实践。









