在Python中,我们可以使用try-except语句进行系统容错处理。当程序出现异常时,可以捕获异常并采取相应的措施。以下是一个简单的爬虫示例,展示了如何使用try-except进行系统容错处理:
import requests from bs4 import BeautifulSoup def get_html(url): try: response = requests.get(url) response.raise_for_status() return response.text except requests.exceptions.RequestException as e: print(f"请求出错: {e}") return None def parse_html(html): try: soup = BeautifulSoup(html, "html.parser") # 在这里解析网页内容,例如提取数据 return soup except Exception as e: print(f"解析出错: {e}") return None def main(): url = "https://example.com" html = get_html(url) if html: soup = parse_html(html) if soup: # 处理解析后的数据 pass if __name__ == "__main__": main()
在这个示例中,我们使用了requests
库来发送HTTP请求,并使用BeautifulSoup
库来解析HTML内容。我们使用try-except语句捕获可能出现的异常,并在出现异常时打印错误信息。这样,即使程序出现异常,也可以继续运行,而不是直接崩溃。