在Python中,使用多線程進行爬蟲時,可以通過threading
模塊來設置線程數。以下是一個簡單的示例:
import threading
import requests
from bs4 import BeautifulSoup
# 定義一個爬蟲函數
def crawl(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 在這里解析網頁內容,提取所需數據
print(f"Visited: {url}")
# 定義一個函數來設置線程數并啟動線程
def start_threads(num_threads, urls):
threads = []
for i in range(num_threads):
thread = threading.Thread(target=crawl, args=(urls[i % len(urls)],))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
if __name__ == "__main__":
urls = [
"https://www.example.com/page1",
"https://www.example.com/page2",
"https://www.example.com/page3",
# 更多URL...
]
num_threads = 5 # 設置線程數
start_threads(num_threads, urls)
在這個示例中,我們首先定義了一個名為crawl
的函數,該函數接受一個URL作為參數,并使用requests
庫獲取網頁內容。然后,我們使用BeautifulSoup
庫解析網頁內容并提取所需數據。
接下來,我們定義了一個名為start_threads
的函數,該函數接受線程數和URL列表作為參數。在這個函數中,我們創建了一個線程列表,并為每個URL創建一個新的線程。我們將crawl
函數作為目標函數,并將URL作為參數傳遞給該函數。然后,我們將每個線程添加到線程列表中,并使用start()
方法啟動線程。
最后,我們遍歷線程列表并使用join()
方法等待所有線程完成。
在__main__
部分,我們定義了一個URL列表,并設置了線程數。然后,我們調用start_threads
函數來啟動線程并執行爬蟲任務。