当前位置: 首页 > article >正文

爬虫抓取数据时如何处理异常?

在爬虫开发中,处理异常是确保爬虫稳定运行的关键环节。爬虫在运行过程中可能会遇到各种问题,例如网络请求失败、目标页面结构变化、数据缺失等。合理处理这些异常可以提高爬虫的鲁棒性,避免因小问题导致整个爬虫程序崩溃。以下是一些常见的异常处理方法和策略:


1. 网络请求异常处理

网络请求是爬虫中最容易出问题的部分,常见的异常包括超时、连接失败、目标服务器返回错误状态码等。

示例代码:
import requests
from requests.exceptions import RequestException

def get_html(url):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
    }
    try:
        response = requests.get(url, headers=headers, timeout=10)  # 设置超时时间
        response.raise_for_status()  # 检查HTTP状态码是否为200
        return response.text
    except RequestException as e:
        print(f"请求失败:{e}")
        return None

处理策略:

  1. 超时设置:通过timeout参数设置请求超时时间,避免爬虫因长时间等待而卡住。

  2. 重试机制:使用requestsSession对象结合urllib3的重试机制。

  3. 状态码检查:通过response.raise_for_status()检查HTTP状态码是否为200。


2. 页面解析异常处理

页面解析过程中可能会遇到HTML结构变化、目标元素缺失等问题,导致BeautifulSoupSelenium抛出异常。

示例代码:
from bs4 import BeautifulSoup

def parse_html(html):
    soup = BeautifulSoup(html, "lxml")
    products = []

    try:
        items = soup.select(".product-item")
        for item in items:
            product = {
                "name": item.select_one(".product-name").text.strip(),
                "price": item.select_one(".product-price").text.strip(),
                "description": item.select_one(".product-description").text.strip()
            }
            products.append(product)
    except AttributeError as e:
        print(f"解析失败:{e}")
    return products

处理策略:

  1. 使用try-except:捕获可能出现的AttributeError等异常。

  2. 检查元素是否存在:在访问元素之前,使用if语句检查元素是否存在。

  3. 日志记录:记录异常信息,便于后续分析和修复。


3. 数据缺失处理

在爬取数据时,可能会遇到某些字段缺失的情况。例如,某些商品可能没有用户评价或图片链接。

示例代码:
def parse_html(html):
    soup = BeautifulSoup(html, "lxml")
    products = []

    items = soup.select(".product-item")
    for item in items:
        product = {
            "name": item.select_one(".product-name").text.strip() if item.select_one(".product-name") else "未知",
            "price": item.select_one(".product-price").text.strip() if item.select_one(".product-price") else "未知",
            "description": item.select_one(".product-description").text.strip() if item.select_one(".product-description") else "无描述"
        }
        products.append(product)
    return products

处理策略:

  1. 使用三元运算符:在提取数据时,检查元素是否存在,避免抛出异常。

  2. 设置默认值:为缺失的字段设置默认值,例如“未知”或“无描述”。


4. 动态内容加载异常处理

如果目标页面使用JavaScript动态加载内容,使用Selenium时可能会遇到页面加载超时、元素未找到等问题。

示例代码:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException, NoSuchElementException

def get_dynamic_html(url):
    options = webdriver.ChromeOptions()
    options.add_argument("--headless")
    driver = webdriver.Chrome(options=options)
    try:
        driver.get(url)
        driver.implicitly_wait(10)  # 设置隐式等待时间
        items = driver.find_elements(By.CSS_SELECTOR, ".product-item")
        for item in items:
            name = item.find_element(By.CSS_SELECTOR, ".product-name").text
            price = item.find_element(By.CSS_SELECTOR, ".product-price").text
            print(f"商品名称:{name}, 价格:{price}")
    except TimeoutException:
        print("页面加载超时")
    except NoSuchElementException:
        print("未找到目标元素")
    finally:
        driver.quit()

处理策略:

  1. 设置隐式等待:通过driver.implicitly_wait()设置隐式等待时间,避免因页面加载缓慢导致元素未找到。

  2. 捕获异常:使用try-except块捕获TimeoutExceptionNoSuchElementException等异常。

  3. 资源清理:在finally块中关闭浏览器实例,确保资源被正确释放。


5. 日志记录

日志记录是爬虫开发中不可或缺的一部分,它可以帮助我们快速定位问题并修复。

示例代码:
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")

def get_html(url):
    headers = {
        "User-Agent": "Mozilla/5.0"
    }
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        return response.text
    except RequestException as e:
        logging.error(f"请求失败:{e}")
        return None

def parse_html(html):
    soup = BeautifulSoup(html, "lxml")
    products = []
    try:
        items = soup.select(".product-item")
        for item in items:
            product = {
                "name": item.select_one(".product-name").text.strip(),
                "price": item.select_one(".product-price").text.strip()
            }
            products.append(product)
    except AttributeError as e:
        logging.error(f"解析失败:{e}")
    return products

处理策略:

  1. 配置日志:使用logging模块配置日志,记录异常信息。

  2. 日志级别:根据需要设置日志级别,例如INFOWARNINGERROR等。

  3. 记录关键信息:在日志中记录关键信息,例如请求URL、异常类型、异常描述等。


6. 异常处理的最佳实践

  1. 明确异常类型:在捕获异常时,尽量明确异常类型,避免使用过于宽泛的except

  2. 合理使用重试机制:对于网络请求等易出错的操作,可以结合重试机制提高成功率。

  3. 资源清理:确保在异常发生时,正确释放资源(如关闭文件、关闭数据库连接、关闭浏览器实例等)。

  4. 容错设计:在爬虫中加入容错设计,即使部分数据无法获取,也不影响整个程序的运行。

  5. 监控与报警:对于长时间运行的爬虫,可以结合监控工具(如Prometheus、Grafana)进行实时监控,并在异常发生时发送报警通知。


总结

合理处理异常是确保爬虫稳定运行的关键。通过捕获网络请求异常、页面解析异常、动态内容加载异常等常见问题,并结合日志记录和容错设计,可以显著提高爬虫的鲁棒性。希望本文的示例和策略能帮助你在爬虫开发中更好地应对各种异常情况,确保爬虫程序的高效、稳定运行。


http://www.kler.cn/a/563737.html

相关文章:

  • C++类与对象深度解析(二):从const 、new 、delete到函数操作符与友元函数的编程实践
  • 蓝桥杯练习代码
  • CSS基础选择器和文字属性控制
  • [U-BOOT][STM32]设置使用SD卡中的linux程序启动
  • 怎样能写出完美的Prompt
  • 鸿蒙中连接手机可能遇到的问题
  • 鸿蒙-AVPlayer
  • SpringBoot整合Mybatis-Plus+Druid实现多数据源
  • MySQL -安装与初识
  • 【linux】文件与目录命令 - sed
  • 基于Flask框架生产环境快速部署
  • React + TypeScript 数据模型驱动数据字典生成示例
  • word中对插入的图片修改背景色
  • Redisson使用场景及原理
  • HTML第二节
  • centos设置 sh脚本开机自启动
  • 算法系列之回溯算法
  • Redis多线程模型演进
  • Dockerfile 中的 COPY 语句:作用与使用详解
  • 基于Django的手办交易平台~源码