溫馨提示×

python爬蟲多線程如何處理異常

小樊
127
2024-12-07 16:06:45
欄目: 編程語言

在Python中,使用多線程處理爬蟲異常時,可以使用concurrent.futures.ThreadPoolExecutortry-except語句。以下是一個簡單的示例:

import requests
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor, as_completed

def fetch(url):
    try:
        response = requests.get(url)
        response.raise_for_status()
        return BeautifulSoup(response.text, 'html.parser')
    except requests.exceptions.RequestException as e:
        print(f"Error fetching {url}: {e}")
        return None

def parse(url):
    soup = fetch(url)
    if soup:
        # 在這里解析網頁內容,例如提取數據
        pass

def main():
    urls = [
        "https://example.com/page1",
        "https://example.com/page2",
        "https://example.com/page3",
        # 更多URL...
    ]

    with ThreadPoolExecutor(max_workers=5) as executor:
        futures = {executor.submit(parse, url): url for url in urls}

        for future in as_completed(futures):
            url = futures[future]
            try:
                future.result()
            except Exception as e:
                print(f"Error processing {url}: {e}")

if __name__ == "__main__":
    main()

在這個示例中,我們首先定義了一個fetch函數,用于獲取網頁內容。我們使用try-except語句捕獲可能的異常,例如網絡錯誤或HTTP錯誤。

接下來,我們定義了一個parse函數,用于解析網頁內容。在這個函數中,我們調用fetch函數并處理可能的異常。

main函數中,我們使用ThreadPoolExecutor創建一個線程池,并將parse函數提交給線程池。我們使用as_completed函數遍歷已完成的任務,并捕獲可能的異常。

這樣,我們可以確保在多線程環境下處理爬蟲異常。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女