在写爬虫时,异常处理几乎不是'可选项',而是必须认真做的一层防线。网络请求会超时,页面结构会变,站点也可能临时返回 403、500 之类的状态。如果没有把这些情况兜住,爬虫很容易跑着跑着就中断了。
下面这个例子演示了一个比较常见的写法:请求页面、检查状态码、解析 HTML,再把商品信息整理成字典返回。
import requests
from bs4 import BeautifulSoup
from requests.exceptions import RequestException
def get_product_details(url):
try:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/58.0.3029.110 Safari/537.3'
}
response = requests.get(url, headers=headers, timeout=10)
# 如果响应状态码不是 200,这里会直接抛出 HTTPError
response.raise_for_status()
soup = BeautifulSoup(response.text, 'lxml')
title = soup.find('div', class_='title').get_text(strip=True)
price = soup.find('span', class_='price').get_text(strip=True)
image = soup.find('img', class_='main-image')['src']
return {
'title': title,
'price': price,
'image': image
}
except RequestException as e:
print(f"请求异常: {e}")
except Exception as e:
print(f"其他异常: ")
:
()
url =
product_details = get_product_details(url)
product_details:
(product_details)
:
()

