在Python中,使用多線程處理爬蟲異常時,可以使用concurrent.futures.ThreadPoolExecutor和try-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函數遍歷已完成的任務,并捕獲可能的異常。
這樣,我們可以確保在多線程環境下處理爬蟲異常。