在Python中,使用多線程進行爬蟲任務隊列管理時,可以利用queue.Queue來實現。以下是一個簡單的示例:
import threading
import requests
from bs4 import BeautifulSoup
import queue
def process_data(data):
# 在這里處理爬取到的數據,例如保存到數據庫或文件
pass
def fetch_url(url, session, q):
try:
response = session.get(url)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
data = soup.title.string # 提取網頁標題作為示例數據
q.put(data)
except Exception as e:
print(f"Error fetching {url}: {e}")
def multi_threaded_crawler(urls, num_threads):
q = queue.Queue()
session = requests.Session()
# 創建線程列表
threads = []
# 啟動線程
for _ in range(num_threads):
t = threading.Thread(target=fetch_url, args=(urls[_], session, q))
t.start()
threads.append(t)
# 等待所有線程完成
for t in threads:
t.join()
# 處理爬取到的數據
while not q.empty():
process_data(q.get())
multi_threaded_crawler函數來執行多線程爬蟲:urls = [
"https://www.example.com",
"https://www.example.org",
"https://www.example.net",
# 更多URL...
]
num_threads = 5
multi_threaded_crawler(urls, num_threads)
這個示例中,我們使用queue.Queue來存儲爬取到的數據,確保數據在多個線程之間安全地傳遞。fetch_url函數負責爬取網頁內容并將其放入隊列中,而process_data函數則負責處理爬取到的數據。multi_threaded_crawler函數負責創建和管理線程,以及等待所有線程完成任務。