多进程 + 多线程抓取博客园信息

2022-10-15,,,,

为每个进程分配一定数量的页面,然后在由进程去给线程分配待抓取页面,抓取到信息之后保存到“博客园.csv”文件中。

第三方模块

aiohttp : 协程模块

beautifulsoup4:解析模块

安装 :

pip install aiohttp

pip install beautifulsoup4

多线程

asyncio协程模块,通过这模块来启用任务并限制线程数量。线程多了影响效率,因为线程是通过时间分片来模拟并行,进程是真并行

多进程

multiprocessing 进程模块通过引用pool类来启用进程池

信息保存

 

 

 

 

部分代码

import page
import asyncio
import os
from asyncrequest import asynchttp
from save import db
from multiprocessing import pool

# 抓取信息
async def fetch(url, attach=none):
    reqs = asynchttp()
    text = await reqs.request(url, attach)
    items = page.fetchlist(text)
    for item in items:
        arc = page.article(item)
        db.writerow({
            '作者': arc.author,
            '头像': arc.icon,
            '地址': arc.url,
            '标题': arc.title,
            '推荐': arc.digg_num,
            '评论': arc.comment_num,
            '阅读': arc.read_num,
            '发布时间': arc.time
        })

# 协程任务
async def core(url, s, e):
    cores = [fetch(url + str(n)) for n in range(s, e)]
    await asyncio.gather(*cores)

# 入口
def main(arg):
    #print(arg[0], arg[1])
    asyncio.semaphore(3)
    asyncio.run(core('https://www.cnblogs.com/sitehome/p/', arg[0], arg[1]))


if __name__ == '__main__':
    with pool(os.cpu_count()) as p:   # 开启最大进程
        arg = [(1, 10), (10, 20), (20, 30), (30, 40)]  # 采用 1~40页
        rep = p.map_async(main, arg)
        rep.get()

 

百度网盘

链接:https://pan.baidu.com/s/1iab8pi1fsfscmp93spux0g
提取码:4x1u

《多进程 + 多线程抓取博客园信息.doc》

下载本文的Word格式文档,以方便收藏与打印。