Python3マルチスレッド処理クローラ

クロール処理では、単一スレッドのみをクロールに使用すると効率が相対的に低くなるため、マルチスレッド クローラー処理方法がよく使用されます。Python3 は、マルチスレッド プログラミングをサポートするためのスレッド モジュールを提供します。Python3 マルチスレッド処理クローラを使用するための一般的な手順は次のとおりです。

依存モジュールをインポートする

import threading
import requests
from queue import Queue

爬虫類を組み立てる

class Spider:
    def __init__(self):
        self.urls = Queue()  # 待爬取的链接队列
        self.results = []  # 存储爬取结果的列表
        self.lock = threading.Lock()  # 线程锁
        self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}

    # 获取链接列表
    def get_urls(self):
        # 这里可以从文件、数据库、网页等方式获取待爬取的链接
        # 这里以一个示例链接列表作为例子
        urls = ['<https://www.example.com/page1>', '<https://www.example.com/page2>', '<https://www.example.com/page3>']
        for url in urls:
            self.urls.put(url)

    # 爬取页面并处理结果
    def crawl(self):
        while not self.urls.empty():
            url = self.urls.get()
            try:
                response = requests.get(url, headers=self.headers)
                # 这里可以对response进行解析,获取需要的信息
                # 这里以抓取页面title作为例子
                title = response.text.split('<title>')[1].split('</title>')[0]
                self.results.append(title)
            except Exception as e:
                print(e)
            finally:
                self.urls.task_done()

    # 启动多线程爬虫
    def run(self, thread_num=10):
        self.get_urls()
        for i in range(thread_num):
            t = threading.Thread(target=self.crawl)
            t.start()
        self.urls.join()

        # 将结果写入文件或者数据库
        with self.lock:
            with open('result.txt', 'a') as f:
                for result in self.results:
                    f.write(result + '\\n')

おすすめ

転載: blog.csdn.net/qq_56920529/article/details/129201627