使用一个列表存储要爬取的网站地址,然后定义一个spider函数,用于处理每个网站的爬取任务。在主程序中,创建多个线程,并使用Thread类创建线程对象。将spider函数作为线程的目标函数,并将要爬取的网站地址作为参数传递给它。然后,使用start方法启动线程,并将线程对象添加到线程列表中。最后,使用join方法等待所有线程完成。
import threading
import requests
from bs4 import BeautifulSoup
# 定义要爬取的网站列表
urls = ['https://www.example1.com', 'https://www.example2.com', 'https://www.example3.com']
# 定义一个爬取函数,用于处理每个网站的爬取任务
def spider(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
links = soup.find_all('a')
for link in links:
text = link.text.strip()
url = link.get('href')
print(f"{text}: {url}")
# 创建多个线程,并分别处理每个网站的爬取任务
threads = []
for url in urls:
t = threading.Thread(target=spider, args=(url,))
t.start()
threads.append(t)
# 等待所有线程完成
for t in threads:
t.join()