在基于 Requests 和 BeautifulSoup 的爬虫项目中,如何设计日志记录和错误处理机制?请给出代码示例。

import logging
from logging.handlers import RotatingFileHandler
import requests
from bs4 import BeautifulSoup
from requests.exceptions import RequestException

def setup_logging():
    """
    配置日志记录工具,支持滚动日志文件。
    """
    # 创建日志记录器
    logger = logging.getLogger('web_scraper')
    logger.setLevel(logging.INFO)
    
    # 设置日志格式
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    
    # 创建文件处理器,限制单个文件大小为1MB,最多保留3个备份
    file_handler = RotatingFileHandler('scraper.log', maxBytes=1*1024*1024, backupCount=3)
    file_handler.setFormatter(formatter)
    
    # 将处理器添加到日志记录器
    logger.addHandler(file_handler)
    
    return logger

def fetch_url(url, logger):
    """
    获取URL的页面内容,并进行错误处理。
    """
    try:
        response = requests.get(url, timeout=5)
        response.raise_for_status()  # 检查HTTP状态码
        logger.info(f"Successfully fetched URL: {url}")
        return response.text
    except RequestException as e:
        logger.error(f"Failed to fetch URL: {url} - Error: {e}")
        return None

def parse_content(html, logger):
    """
    解析HTML内容,提取所需数据。
    """
    try:
        soup = BeautifulSoup(html, 'html.parser')
        title = soup.title.string if soup.title else "No title found"
        logger.info(f"Successfully parsed content, title: {title}")
        return title
    except Exception as e:
        logger.error(f"Failed to parse content - Error: {e}")
        return None

def main():
    """
    主函数,执行爬虫任务。
    """
    logger = setup_logging()
    url = "https://example.com"
    
    html = fetch_url(url, logger)
    if html:
        title = parse_content(html, logger)
        if title:
            logger.info(f"Extracted title: {title}")
    
    logger.info("Scraping completed.")

if __name__ == "__main__":
    main()

设计说明

  1. 日志记录机制:

    • 使用Python的logging模块配置日志记录,支持滚动日志文件(RotatingFileHandler),确保日志文件不会过大。
    • 日志内容包括时间戳、日志级别和消息,便于排查问题。
    • 日志文件限制为每个1MB,最多保留3个备份。
  2. 错误处理机制:

    • 在fetch_url函数中,捕获RequestException异常(例如超时、网络错误等),并记录错误日志。
    • 在parse_content函数中,捕获通用的Exception异常,防止解析错误导致程序崩溃。
    • 每个错误都附带详细的上下文信息,便于定位问题。
  3. 逻辑分离:

    • 将日志配置、URL获取和内容解析功能分离,代码结构清晰且易于维护。

示例运行

假设访问的URL是https://example.com,可能的日志输出如下:

2023-10-01 12:00:00 - INFO - Successfully fetched URL: https://example.com
2023-10-01 12:00:01 - INFO - Successfully parsed content, title: Example Domain
2023-10-01 12:00:01 - INFO - Extracted title: Example Domain
2023-10-01 12:00:01 - INFO - Scraping completed.

如果网络请求失败,日志会记录错误:

2023-10-01 12:00:00 - ERROR - Failed to fetch URL: https://example.com - Error: Connection timed out
2023-10-01 12:00:00 - INFO - Scraping completed.

通过这种方式,可以高效地记录爬虫的运行状态和错误,便于后期分析和优化。