多进程爬虫效果展示

博客展示了不同进程数量的爬虫耗时情况。串行爬虫耗时13.354042291641235,两个进程爬虫耗时7.521216869354248,四个进程耗时3.670652151107788,八个进程耗时2.4657177925109863,16个进程耗时1.6584398746490479。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import requests
import re
import time
from multiprocessing import Pool

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36'
}


def re_scraper(url):
    res = requests.get(url, headers=headers)
    ids = re.findall('<h2>(.*?)</h2>', res.text, re.S)
    contents = re.findall('<div class="content"><span>(.*?)</span></div>', res.text, re.S)
    laughts = re.findall('<span class="stats-vote"><i class="number">(\d+)</i>', res.text, re.S)
    comments = re.findall('<i class="number">(\d+)</i>评论', res.text, re.S)
    for id, content, laught, comment in zip(ids, contents, laughts, comments):
        info = {
            'id': id,
            'content': content,
            'laught': laught,
            'comment': comment
        }
    # 只爬取,不存储,测试性能
    return


if __name__ == '__main__':
    urls = ['https://www.qiushibaike.com/text/page/{}/'.format(str(i)) for i in range(1, 36)]
    start_1 = time.time()
    for url in urls:
        re_scraper(url)
    end_1 = time.time()
    print("串行爬虫耗费时间:", end_1 - start_1)
    start_2 = time.time()
    pool = Pool(processes=2)
    pool.map(re_scraper, urls)
    end_2 = time.time()
    print("两个进程爬虫耗费时间:", end_2 - start_2)
    start_3 = time.time()
    pool = Pool(processes=4)
    pool.map(re_scraper, urls)
    end_3 = time.time()
    print("四个进程爬虫耗费时间:", end_3 - start_3)
    start_4= time.time()
    pool = Pool(processes=8)
    pool.map(re_scraper, urls)
    end_4 = time.time()
    print("八个进程爬虫耗费时间:", end_4 - start_4)
    start_5 = time.time()
    pool = Pool(processes=16)
    pool.map(re_scraper, urls)
    end_5 = time.time()
    print("16个进程爬虫耗费时间:", end_5 - start_5)

 output:

串行爬虫耗费时间: 13.354042291641235
两个进程爬虫耗费时间: 7.521216869354248
四个进程爬虫耗费时间: 3.670652151107788
八个进程爬虫耗费时间: 2.4657177925109863
16个进程爬虫耗费时间: 1.6584398746490479

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值