为每个进程分配一定数量的页面,然后在由进程去给线程分配待抓取页面,抓取到信息之后保存到“博客园.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