• 交通 | python网络爬虫:“多线程并行 + 多线程异步协程


    推文作者:Amiee

    编者按:

    常规爬虫都是爬完一个网页接着爬下一个网页,不适应数据量大的网页,本文介绍了多线程处理同时爬取多个网页的内容,提升爬虫效率。

    1.引言​


    一般而言,常规爬虫都是爬完一个网页接着爬下一个网页。如果当爬取的数据量非常庞大时,爬虫程序的时间开销往往很大,这个时候可以通过多线程或者多进程处理即可完成多个网页内容同时爬取的效果,数据获取速度大大提升。​


    2.基础知识​


    简单来说,CPU是进程的父级单位,一个CPU可以控制多个进程;进程是线程的父级单位,一个进程可以控制多个线程,那么到底什么是进程,什么是线程呢?​


    对于操作系统来说,一个任务就是一个进程(Process),比如打开一个浏览器就是启动一个浏览器进程;打开一个QQ就启动一个QQ进程;打开一个Word就启动了一个Word进程,打开两个Word就启动两个Word进程。​


    那什么叫作线程呢?在一个进程内部往往不止同时干一件事,比如浏览器,它可以同时浏览网页、听音乐、看视频、下载文件等。在一个进程内部这同时运行的多个“子任务”,便称之称为线程(Thread),线程是程序工作的最小单元。​


    此外有个注意点,对于单个CPU而言,某一个时点只能执行一个任务,那么如果这样是怎么在现实中同时执行多个任务(进程)的呢?比如一边用浏览器听歌,一边用QQ和好友聊天是如何实现的呢?​


    答案是操作系统会通过调度算法,轮流让各个任务(进程)交替执行。以时间片轮转算法为例:有5个正在运行的程序(即5个进程) : QQ、微信、谷歌浏览器、网易云音乐、腾讯会议,操作系统会让CPU轮流来调度运行这些进程,一个进程每次运行0.1ms,因为CPU执行的速度非常快,这样看起来就像多个进程同时在运行。同理,对于多个线程,例如通过谷歌浏览器(进程)可以同时访问网页(线程1)、听在线音乐(线程2)和下载网络文件(线程3)等操作,也是通过类似的时间片轮转算法使得各个子任务(线程)近似同时执行。​


    2.1 Thread()版本案例

    1. from threading import Thread
    2. def func():
    3. for i in range(10):
    4. print('func', i)
    5. if name == '__main__':
    6. t = Thread(target=func) # 创建线程
    7. t.start() # 多线程状态,可以开始工作了,具体时间有CPU决定
    8. for i in range(10):
    9. print('main', i)
    10. 执行结果如下:
    11. func 0
    12. func 1
    13. func 2
    14. func 3
    15. func 4
    16. main 0
    17. main 1
    18. main 2
    19. main 3
    20. main 4
    21. mainfunc 5 5
    22. func
    23. main 66
    24. func 7
    25. main
    26. func 8
    27. func 9
    28. 7
    29. main 8
    30. main 9

    2.2 MyTread() 版本案例​


    大佬是这个写法

    1. from threading import Thread​
    2. class MyThread(Thread):​
    3. def run(self):​
    4. for i in range(10):​
    5. print('MyThread', i)​
    6. if name == '__main__':​
    7. t = MyThread()​
    8. # t.run() # 调用run就是单线程​
    9. t.start() # 开启线程​
    10. for i in range(10):​
    11. print('main', i)​
    12. 执行结果:​
    13. MyThread 0
    14. MyThread 1
    15. MyThread 2
    16. MyThread 3
    17. MyThread 4
    18. MyThread 5main 0
    19. main 1
    20. main 2
    21. main 3
    22. main 4
    23. MyThread ​
    24. main 5
    25. 6
    26. main MyThread 67
    27. mainMyThread 78
    28. mainMyThread 89
    29. main 9

    2.3 带参数的多线程版本

    1. from threading import Thread
    2. def func(name):
    3. for i in range(10):
    4. print(name, i)
    5. if name == '__main__':
    6. t1 = Thread(target=func, args=('子线程1',)) # 创建线程
    7. t1.start() # 多线程状态,可以开始工作了,具体时间又CPU决定
    8. t2 = Thread(target=func, args=('子线程2',)) # 创建线程
    9. t2.start() # 多线程状态,可以开始工作了,具体时间又CPU决定
    10. for i in range(10):
    11. print('main', i)

    2.4 多进程

    一般不建议使用,因为开进程比较费资源

    1. from multiprocessing import Process
    2. def func():
    3. for i in range(1000000):
    4. print('func', i)
    5. if name == '__main__':
    6. p = Process(target=func)
    7. p.start() # 开启线程
    8. for i in range(100000):
    9. print('mainn process', i)

    3. 线程池和进程池

    线程池:一次性开辟一些线程,我们用户直接给线程池提交任务,线程任务的调度由线程池来完成

    1. from concurrent.futures import ThreadPoolExecutor
    2. def func(name):
    3. for i in range(10):
    4. print(name, i)
    5. if name == '__main__':
    6. # 创建线程池
    7. with ThreadPoolExecutor(50) as t:
    8. for i in range(100):
    9. t.submit(func, name=f'Thread{i}=')
    10. # 等待线程池中的人物全部执行完成,才继续执行;也称守护进程
    11. print('执行守护线程')

    进程池

    1. from concurrent.futures import ProcessPoolExecutor
    2. def func(name):
    3. for i in range(10):
    4. print(name, i)
    5. if name == '__main__':
    6. # 创建线程池
    7. with ProcessPoolExecutor(50) as t:
    8. for i in range(100):
    9. t.submit(func, name=f'Thread{i}=')
    10. # 等待线程池中的人物全部执行完成,才继续执行;也称守护进程
    11. print('执行守护进程')

    4. 爬虫实战-爬取新发地菜价

    单个线程怎么办;上线程池,多个页面同时爬取

    1. import requests
    2. from lxml import etree
    3. import csv
    4. from concurrent.futures import ThreadPoolExecutor
    5. f = open('xifadi.csv', mode='w', newline='')
    6. csv_writer = csv.writer(f)
    7. def download_one_page(url):
    8. resp = requests.get(url)
    9. resp.encoding = 'utf-8'
    10. html = etree.HTML(resp.text)
    11. table = html.xpath(r'/html/body/div[2]/div[4]/div[1]/table')[0]
    12. # trs = table.xpath(r'./tr')[1:] # 跳过表头
    13. trs = table.xpath(r'./tr[position()>1]')
    14. for tr in trs:
    15. td = tr.xpath('./td/text()')
    16. # 处理数据中的 \\ 或 /
    17. txt = (item.replace('\\','').replace('/','') for item in td)
    18. csv_writer.writerow(txt)
    19. resp.close()
    20. print(url, '提取完毕')
    21. if name == '__main__':
    22. with ThreadPoolExecutor(50) as t:
    23. for i in range(1, 200):
    24. t.submit(download_one_page,f'http://www.xinfadi.com.cn/marketanalysis/0/list/{i}.shtml')
    25. print('全部下载完毕')

    5. python网络爬虫:多线程异步协程与实验案例​


    5.1 基础理论​


    程序处于阻塞状态的情形包含以下几个方面:​
    •input():等待用户输入​
    •requests.get():网络请求返回数据之前​
    •当程序处理IO操作时,线程都处于阻塞状态​
    •time.sleep():处于阻塞状态​

    协程的逻辑是当程序遇见IO操作时,可以选择性的切换到其他任务上;协程在微观上任务的切换,切换条件一般就是IO操作;在宏观上,我们看到的是多个任务都是一起执行的;上方的一切都是在在单线程的条件下,充分的利用单线程的资源。​

    要点梳理:​
    •函数被asyn修饰,函数被调用时,它不会被立即执行;该函数被调用后会返回一个协程对象。​
    •创建一个协程对象:构建一个asyn修饰的函数,然后调用该函数返回的就是一个协程对象​
    •任务对象是一个高级的协程对象,

    1. import asyncio​
    2. import time
    3. async def func1():​
    4. print('你好呀11')​
    5. if name == '__main__':​
    6. g1 = func1() # 此时的函数是异步协程函数,此时函数执行得到的是一个协程对象​
    7. asyncio.run(g1) # 协程城西执行需要asyncio模块的支持

    5.2 同步/异步睡眠​

    普通的time.sleep()是同步操作,会导致异步操作中断

    1. import asyncio
    2. import time
    3. async def func1():
    4. print('你好呀11')
    5. time.sleep(3) # 当程序中除了同步操作时,异步就中端了
    6. print('你好呀12')
    7. async def func2():
    8. print('你好呀21')
    9. time.sleep(2)
    10. print('你好呀22')
    11. async def func3():
    12. print('你好呀31')
    13. time.sleep(4)
    14. print('你好呀32')
    15. if name == '__main__':
    16. g1 = func1() # 此时的函数是异步协程函数,此时函数执行得到的是一个协程对象
    17. g2 = func2()
    18. g3 = func3()
    19. tasks = [g1, g2, g3]
    20. t1 = time.time()
    21. asyncio.run(asyncio.wait(tasks)) # 协程城西执行需要asyncio模块的支持
    22. t2 = time.time()
    23. print(t2 - t1)
    24. 你好呀21
    25. 你好呀22
    26. 你好呀11
    27. 你好呀12
    28. 你好呀31
    29. 你好呀32
    30. 9.003259658813477

    使用异步睡眠函数,遇到睡眠时,挂起;

    1. import asyncio
    2. import time
    3. async def func1():
    4. print('你好呀11')
    5. await asyncio.sleep(3) # 异步模块的sleep
    6. print('你好呀12')
    7. async def func2():
    8. print('你好呀21'))
    9. await asyncio.sleep(4) # 异步模块的sleep
    10. print('你好呀22')
    11. async def func3():
    12. print('你好呀31')
    13. await asyncio.sleep(4) # 异步模块的sleep
    14. print('你好呀32')
    15. if name == '__main__':
    16. g1 = func1() # 此时的函数是异步协程函数,此时函数执行得到的是一个协程对象
    17. g2 = func2()
    18. g3 = func3()
    19. tasks = [g1, g2, g3]
    20. t1 = time.time()
    21. asyncio.run(asyncio.wait(tasks)) # 协程城西执行需要asyncio模块的支持
    22. t2 = time.time()
    23. print(t2 - t1)
    24. 你好呀21
    25. 你好呀11
    26. 你好呀31
    27. 你好呀12
    28. 你好呀22
    29. 你好呀32
    30. 4.0028839111328125

    整体耗时为最长时间 + 切换时间

    5.3 官方推荐多线程异步协程写法

    1. import asyncio
    2. import time
    3. async def func1():
    4. print('你好呀11')
    5. # time.sleep(3) # 当程序中除了同步操作时,异步就中端了
    6. await asyncio.sleep(3) # 异步模块的sleep
    7. print('你好呀12')
    8. async def func2():
    9. print('你好呀21')
    10. # time.sleep(2)
    11. await asyncio.sleep(4) # 异步模块的sleep
    12. print('你好呀22')
    13. async def func3():
    14. print('你好呀31')
    15. # time.sleep(4)
    16. await asyncio.sleep(4) # 异步模块的sleep
    17. print('你好呀32')
    18. async def main():
    19. # 写法1:不推荐
    20. # f1 = func1()
    21. # await f1 # await挂起操作,一般放在协程对象前边
    22. # 写法2:推荐,但是在3.8废止,3.11会被移除
    23. # tasks = [func1(), func2(), func3()]
    24. # await asyncio.wait(tasks)
    25. # 写法3:python3.8以后使用
    26. tasks = [asyncio.create_task(func1()),
    27. asyncio.create_task(func2()),
    28. asyncio.create_task(func3())]
    29. await asyncio.wait(tasks))
    30. if name == '__main__':
    31. t1 = time.time()
    32. asyncio.run(main())
    33. t2 = time.time()
    34. print(t2 - t1)
    35. 你好呀21
    36. 你好呀31
    37. 你好呀11
    38. 你好呀12
    39. 你好呀32
    40. 你好呀22
    41. 4.001523017883301

    6. 异步协程爬虫实战

    安装包:

    pip install aiohttp

    pip install aiofiles

    基本框架:​
    •获取所有的url​
    •编写每个url的爬取函数​
    •每个url建立一个线程任务,爬取数据

    6.1 爬取图片实战代码

    1. import asyncio
    2. import aiohttp
    3. import aiofiles
    4. headers = {'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Mobile Safari/537.36 Edg/91.0.864.41'}
    5. urls = {
    6. r'http://kr.shanghai-jiuxin.com/file/mm/20210503/xy2edb1kuds.jpg',
    7. r'http://kr.shanghai-jiuxin.com/file/mm/20210503/g4ok0hh2utm.jpg',
    8. r'http://kr.shanghai-jiuxin.com/file/mm/20210503/sqla2defug0.jpg',
    9. r'http://d.zdqx.com/aaneiyi_20190927/001.jpg'
    10. }
    11. async def aio_download(url):
    12. async with aiohttp.ClientSession() as session:
    13. async with session.get(url, headers=headers) as resp:
    14. async with aiofiles.open('img/' + url.split('/')[-1],mode='wb') as f:
    15. await f.write(await resp.content.read())
    16. await f.close() # 异步代码需要关闭文件,否则会输出0字节的空文件
    17. # with open(url.split('/')[-1],mode='wb') as f: # 使用with代码不用关闭文件
    18. # f.write(await resp.content.read()) # 等价于resp.content, resp.json(), resp.text()
    19. async def main():
    20. tasks = []
    21. for url in urls:
    22. tasks.append(asyncio.create_task(aio_download(url)))
    23. await asyncio.wait(tasks)
    24. if name == '__main__':
    25. # asyncio.run(main()) # 可能会报错 Event loop is closed 使用下面的代码可以避免
    26. asyncio.get_event_loop().run_until_complete(main())
    27. print('over')

    知识点总结:​
    •在python 3.8以后,建议使用asyncio.create_task()创建人物​
    •aiofiles写文件,需要关闭文件,否则会生成0字节空文件​
    •aiohttp中生成图片、视频等文件时,使用resp.content.read(),而requests库时,并不需要read()​
    •报错 Event loop is closed时, 将 asyncio.run(main()) 更改为 asyncio.get_event_loop().run_until_complete(main())​
    •使用with打开文件时,不用手动关闭

    6.2 爬取百度小说

    注意:以下代码可能会因为 百度阅读 页面改版而无法使用

    主题思想:

    • 分析那些请求需要异步,那些不需要异步;在这个案例中,获取目录只需要请求一次,所以不需要异步

    • 下载每个章节的内容,则需要使用异步操作

    1. import requests
    2. import asyncio
    3. import aiohttp
    4. import json
    5. import aiofiles

    https://dushu.baidu.com/pc/detail?gid=4306063500

    http://dushu.baidu.com/api/pc/getCatalog?data={"book_id":"4306063500"} 获取章节的名称,cid;只请求1次,不需要异步

    http://dushu.baidu.com/api/pc/getChapterContent # 涉及多个任务分发,需要异步请求,拿到所有的文章内容

    1. headers = {'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Mobile Safari/537.36 Edg/91.0.864.41'}
    2. async def aio_download(cid, book_id,title):
    3. data = {
    4. 'book_id': book_id,
    5. 'cid' : f'{book_id}|{cid}',
    6. 'need_bookinfo': 1
    7. }
    8. data = json.dump(data)
    9. url = f'http://dushu.baidu.com/api/pc/getChapterContent?data={data}'
    10. async with aiohttp.ClientSession as session:
    11. async with session.get(url) as resp:
    12. dic = await resp.json()
    13. async with aiofiles.open('img/'+title+'.txt',mode='w') as f:
    14. await f.write(dic['data']['novel']['content'])
    15. await f.close()
    16. async def getCatalog(url):
    17. resp = requests.get(url, headers=headers)
    18. dic = resp.json()
    19. tasks = []
    20. for item in dic['data']['novel']['items']:
    21. title = item['title']
    22. cid = item['cid']
    23. tasks.append(asyncio.create_task(aio_download((cid, book_id,title))))
    24. await asyncio.wait(tasks)
    25. if name == '__main__':
    26. book_id = '4306063500'
    27. url = r'http://dushu.baidu.com/api/pc/getCatalog?data={"book_id":"'+book_id+'"}'
    28. asyncio.run(getCatalog(url))

  • 相关阅读:
    ISPE GAMP5 中文版
    SQL每日一练(牛客新题库)——第1天: 基础查询
    云计算,用价格让利换创新空间?
    tensorflow安装以及在Anaconda中安装使用
    接口获取数据,转成JSONOBJECT
    【Python练习】task-07 函数的扩展应用
    Neo4j CQl语句(持续更新)
    NumPy学习挑战第一关-NumPy的下载与安装
    Contest2850 - 【在线编程平台】2022年计算机类数据结构作业12.20221201-1206
    GitHub 报告发布:TypeScript 取代 Java 成为第三受欢迎语言
  • 原文地址:https://blog.csdn.net/weixin_53463894/article/details/133819715