「Python」爬虫-6.爬虫效率的提高

简介: > 本文主要介绍如何提高爬虫效率的问题,主要涉及到的知识为多线程、线程池、进程池以及协程等。

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第19天, 点击查看活动详情

本文主要介绍如何提高爬虫效率的问题,主要涉及到的知识为多线程、线程池、进程池以及协程等。

关于爬虫相关,欢迎先阅读一下我的前几篇文章😶‍🌫️😶‍🌫️😶‍🌫️:

「Python」爬虫-1.入门知识简介 - 掘金 (juejin.cn)

「Python」爬虫-2.xpath解析和cookie,session - 掘金 (juejin.cn)

「Python」爬虫-3.防盗链处理 - 掘金 (juejin.cn)

「Python」爬虫-4.selenium的使用 - 掘金 (juejin.cn)

「Python」爬虫-5.m3u8(视频)文件的处理 - 掘金 (juejin.cn)

参考文章:

进程和线程、协程的区别 - RunningPower - 博客园 (cnblogs.com)


首先对线程,进程,协程做一个简单的区分吧:

进程资源单位,每一个进程至少要有一个线程,每个进程都有自己的独立内存空间,不同进程通过进程间通信来通信。

线程执行单位,启动每一个程序默认都会有一个主线程。线程间通信主要通过共享内存,上下文切换很快,资源开销较少,但相比进程不够稳定容易丢失数据。

协程是一种用户态的轻量级线程, 协程的调度完全由用户控制。协程拥有自己的寄存器上下文和栈。协程调度切换时,将寄存器上下文和栈保存到其他地方,在切回来的时候,恢复先前保存的寄存器上下文和栈,直接操作栈则基本没有内核切换的开销,可以不加锁的访问全局变量,所以上下文的切换非常快。


了解了进程、线程、协程之间的区别之后,我们就可以思考如何用这些东西来提高爬虫的效率呢?

爬虫效率的提高

多线程

要体现多线程的特点就必须得拿单线程来做一个比较,这样才能凸显不同~

单线程运行举例:

 def func():
     for i in range(5):
         print("func", i)


 if __name__ == '__main__':
     func()
     for i in range(5):
         print("main", i)

运行结果如下:

# 单线程演示案例
result:
func 0
func 1
func 2
func 3
func 4
main 0
main 1
main 2
main 3
main 4

可以注意到在单线程的情况下,程序是先打印fun 0 - 4, 再打印main 0 - 4。

下面再举一个多线程的🌰:

需要实例化一个Thread类 Thread(target=func()) target接收的就是任务(/函数),通过.start()方法就可以启动多线程了。

代码提供两种方式:

# 多线程(两种方法)
# 方法一:
 from threading import Thread

 def func():
     for i in range(1000):
         print("func ", i)

 if __name__ == '__main__':
     t = Thread(target=func())  # 创建线程并给线程安排任务
     t.start()  # 多线程状态为可以开始工作状态,具体的执行时间由CPU决定  
     for i in range(1000):
         print("main ", i)
# two
class MyThread(Thread):
    def run(self): # 固定的  -> 当线程被执行的时候,被执行的就是run()
        for i in range(1000):
            print("子线程 ", i)


if __name__ == '__main__':
    t = MyThread()
    # t.run()  #方法调用 --》单线程
    t.start()  #开启线程
    for i in range(1000):
        print("主线程 ", i)

运行结果

image.png

子线程和主线程有时候会同时执行,这就是多线程吧

线程创建之后只是代表处于能够工作的状态,并不代表立即执行,具体执行的时间需要看CPU

感觉线程执行的顺序就是杂乱无章的。


接下来分享一下多进程:

多进程

进程的使用:Process(target=func())

先举一个🌰来感受一下多进程的执行顺序:

from multiprocessing import Process

def func():
    for i in range(1000):
        print("子进程 ", i)

if __name__ == '__main__':
    p = Process(target=func())
    p.start()
    for i in range(1000):
        print("主进程 ", i)

运行结果:

image.png

从结果中可以发出,所有的子进程按照顺序执行之后。就开始打印主进程0-999。进程打印的有序也表明线程是最小的执行单位。

开启多线程打印的时候,出现的数字并不是有序的。

线程池&进程池

在python中一般使用以下方法创建线程池/进程池:

with ThreadPoolExecutor(50) as t:
     t.submit(fn, name=f"线程{i}")

具体代码:

# 线程池:一次性开辟一些线程,我们用户直接给线程池提交任务,线程任务的调度交给线程池来完成
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor

def fn(name):
    for i in range(1000):
        print(name,i)

if __name__ == '__main__':
    # 创建线程池
    with ThreadPoolExecutor(50) as t:
        for i in range(100):
            t.submit(fn, name=f"线程{i}")
    # 等待线程池中的任务全部执行完毕,才继续执行(守护)
    print(123)

image.png

进程池的创建方法类似。


协程

协程:当程序遇见IO操作的时候,可以选择性的切换到其他任务上。

在微观上是一个任务一个任务的进行切换,切换条件一般就是IO操作

在宏观上,我们能看到的其实就是多个任务一起在执行,
多任务异步操作(就像你自己一边洗脚一边看剧一样~,时间管理带师(bushi

线程阻塞的一些案例:

🌰1:

time.sleep(30)    # 让当前线程处于阻塞状态,CPU是不为我工作的
# input()    程序也是处于阻塞状态
# requests.get(xxxxxx) 在网络请求返回数据之前,程序也是处于阻塞状态
# 一般情况下,当程序处于IO操作的时候,线程都会处于阻塞状态
# for example: 边洗脚边按摩
import asyncio
import time

async def func():
     print("hahha")

if __name__ == "__main__":
     g = func()  # 此时的函数是异步协程函数,此时函数执行得到的是一个协程对象
     asyncio.run(g) # 协程程序运行需要asyncio模块的支持

输出结果:

root@VM-12-2-ubuntu:~/WorkSpace# python test.py
hahha

🌰2:

 async def func1():
     print("hello,my name id hanmeimei")
     # time.sleep(3)  # 当程序出现了同步操作的时候,异步就中断了
     await asyncio.sleep(3)  # 异步操作的代码
     print("hello,my name id hanmeimei")


 async def func2():
     print("hello,my name id wahahha")
     # time.sleep(2)
     await asyncio.sleep(2)  # 异步操作的代码
     print("hello,my name id wahahha")


 async def func3():
     print("hello,my name id hhhhhhhc")
     # time.sleep(4)
     await asyncio.sleep(4)  # 异步操作的代码
     print("hello,my name id hhhhhhhc")


 if __name__ == "__main__":
     f1 = func1()
     f2 = func2()
     f3 = func3()
     task = [
         f1, f2, f3
     ]
     t1 = time.time()
     asyncio.run(asyncio.wait(task))
     t2 = time.time()
     print(t2 - t1)

运行结果:
image.png

注意到执行await asyncio.sleep(4)后,主程序就会调用其他函数了。成功实现了异步操作。(边洗脚边按摩bushi )

下面的代码看起来更为规范~

async def func1():
    print("hello,my name id hanmeimei")
    await asyncio.sleep(3)
    print("hello,my name id hanmeimei")


async def func2():
    print("hello,my name id wahahha")
    await asyncio.sleep(2)
    print("hello,my name id wahahha")


async def func3():
    print("hello,my name id hhhhhhhc")
    await asyncio.sleep(4)
    print("hello,my name id hhhhhhhc")


async def main():
    # 第一种写法
    # f1 = func1()
    # await f1 # 一般await挂起操作放在协程对象前面
    # 第二种写法(推荐)
    tasks = [
        func1(),   # py3.8以后加上asyncio.create_task()
        func2(),
        func3()
    ]
    await asyncio.wait(tasks)


if __name__ == "__main__":
    t1 = time.time()
    asyncio.run(main())
    t2 = time.time()
    print(t2 - t1)

再举一个模拟下载的🌰吧,更加形象啦:

async def download(url):
    print("准备开始下载")
    await asyncio.sleep(2) # 网络请求
    print("下载完成")

async def main():
    urls = [
        "http://www.baidu.com",
        "http://www.bilibili.com",
        "http://www.163.com"
    ]
    tasks = []
    for url in urls:
        d = download(url)
        tasks.append(d)

    await asyncio.wait(tasks)

if __name__ == '__main__':
    asyncio.run(main())
# requests.get()  同步的代码 => 异步操作aiohttp

import asyncio
import aiohttp

urls = [
    "http://kr.shanghai-jiuxin.com/file/2020/1031/191468637cab2f0206f7d1d9b175ac81.jpg",
    "http://i1.shaodiyejin.com/uploads/tu/201704/9999/fd3ad7b47d.jpg",
    "http://kr.shanghai-jiuxin.com/file/2021/1022/ef72bc5f337ca82f9d36eca2372683b3.jpg"
]


async def aiodownload(url):
    name = url.rsplit("/", 1)[1]  # 从右边切,切一次,得到[1]位置的内容 fd3ad7b47d.jpg
    async with aiohttp.ClientSession() as session: # requests
        async with session.get(url) as resp: # resp = requests.get()
            # 请求回来之后,写入文件
            # 模块 aiofiles
            with open(name, mode="wb") as f: # 创建文件
                f.write(await resp.content.read())  # 读取内容是异步的,需要将await挂起, resp.text()
    print(name, "okk")
            # resp.content.read() ==> resp.text()
    # s = aiphttp.ClientSession <==> requests
    # requests.get()  .post()
    # s.get()  .post()
    # 发送请求
    # 保存图片内容平
    # 保存为文件


async def main():
    tasks = []
    for url in urls:
        tasks.append(aiodownload(url))
    await asyncio.wait(tasks)


if __name__ == '__main__':
    asyncio.run(main())

最后再来利用协程实现爬取异步小说的案例

案例:协程爬取一部小说

# 协程-爬取一部小说
# "https://dushu.baidu.com/api/pc/getCatalog?data={"book_id":"4305592439"}  => 所有章节的内容(名称,cid)
# 章节内部的内容
# https://dushu.baidu.com/api/pc/getChapterContent?data={"book_id":"4305592439","cid":"4305592439|10525845","need_bookinfo":"1"}

import requests
import os
import aiohttp
import aiofiles
import asyncio
import json

"""
1.同步操作:访问getCatalog 拿到所有章节的cid和名称
2.异步操作:访问getChapterContent 
"""


async def aiodownload(cid, b_id, title):
    data = {
        "book_id": b_id,
        "cid": f"{b_id}|{cid}",
        "need_bookinfo": 1
    }
    data = json.dumps(data)
    url = f"https://dushu.baidu.com/api/pc/getChapterContent?data={data}"

    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            dic = await resp.json()
            async with aiofiles.open(title, mode="w", encoding="utf-8") as f:
                os.chdir(f"D:/python/workSpace/study_demo/base/book_demos/demo/novel")
                await f.write(dic['data']['novel']['content'])


async def getCatalog(url):
    resp = requests.get(url)
    dic = resp.json()
    tasks = []
    for item in dic['data']['novel']['items']:  # item 就是对应每一个章节的名称和cid
        title = item['title']
        cid = item['cid']
        # 准备异步任务
        tasks.append(aiodownload(cid, b_id, title))
    await asyncio.wait(tasks)


if __name__ == '__main__':
    b_id = "4305592439"
    url = 'https://dushu.baidu.com/api/pc/getCatalog?data={"book_id":"' + b_id + '"}'
    loop = asyncio.get_event_loop()
    loop.run_until_complete(getCatalog(url))
    # asyncio.run(getCatalog(url))

补充知识-json:

json.dumps将一个 Python数据结构转换为JSON

image.png
json.dump()和json.dumps()的区别

json.dumps() 是把python对象转换成json对象的一个过程,生成的是字符串。
json.dump() 是把python对象转换成json对象生成一个fp的文件流,和文件相关。

import json

x = {'name':'你猜','age':19,'city':'四川'}
#用dumps将python编码成json字符串
y = json.dumps(x)
print(y)
i = json.dumps(x,separators=(',',':'))
print(i)
"""
输出结果
{"name": "\u4f60\u731c", "age": 19, "city": "\u56db\u5ddd"}
{"name":"\u4f60\u731c","age":19,"city":"\u56db\u5ddd"}
"""
关于线程,进程,协程就写到这儿啦,如果对你有帮助的吧,就留下你的足迹吧~⛷️⛷️⛷️

---

往期好文推荐🪶

「MongoDB」Win10版安装教程

「Python」数字推盘游戏

「Python」sklearn第一弹-标准化和非线性转化

「Python」turtle绘制图形🎈

「Python」Pandas-DataFrame的相关操作二

相关文章
|
2天前
|
数据采集 XML 数据处理
使用Python实现简单的Web爬虫
本文将介绍如何使用Python编写一个简单的Web爬虫,用于抓取网页内容并进行简单的数据处理。通过学习本文,读者将了解Web爬虫的基本原理和Python爬虫库的使用方法。
|
2天前
|
数据采集 Web App开发 数据处理
Lua vs. Python:哪个更适合构建稳定可靠的长期运行爬虫?
Lua vs. Python:哪个更适合构建稳定可靠的长期运行爬虫?
|
2天前
|
数据采集 Web App开发 Java
Python 爬虫:Spring Boot 反爬虫的成功案例
Python 爬虫:Spring Boot 反爬虫的成功案例
|
2天前
|
数据采集 Python
使用Python实现简单的Web爬虫
本文将介绍如何使用Python编写一个简单的Web爬虫,用于抓取网页上的信息。通过分析目标网页的结构,利用Python中的requests和Beautiful Soup库,我们可以轻松地提取所需的数据,并将其保存到本地或进行进一步的分析和处理。无论是爬取新闻、股票数据,还是抓取图片等,本文都将为您提供一个简单而有效的解决方案。
|
2天前
|
数据采集 存储 XML
如何利用Python构建高效的Web爬虫
本文将介绍如何使用Python语言以及相关的库和工具,构建一个高效的Web爬虫。通过深入讨论爬虫的基本原理、常用的爬虫框架以及优化技巧,读者将能够了解如何编写可靠、高效的爬虫程序,实现数据的快速获取和处理。
|
2天前
|
数据采集 Web App开发 数据可视化
Python爬虫技术与数据可视化:Numpy、pandas、Matplotlib的黄金组合
Python爬虫技术与数据可视化:Numpy、pandas、Matplotlib的黄金组合
|
2天前
|
数据采集 存储 大数据
Python爬虫:数据获取与解析的艺术
本文介绍了Python爬虫在大数据时代的作用,重点讲解了Python爬虫基础、常用库及实战案例。Python因其简洁语法和丰富库支持成为爬虫开发的优选语言。文中提到了requests(发送HTTP请求)、BeautifulSoup(解析HTML)、Scrapy(爬虫框架)、Selenium(处理动态网页)和pandas(数据处理分析)等关键库。实战案例展示了如何爬取电商网站的商品信息,包括确定目标、发送请求、解析内容、存储数据、遍历多页及数据处理。最后,文章强调了遵守网站规则和尊重隐私的重要性。
30 2
|
2天前
|
数据采集 定位技术 Python
Python爬虫IP代理技巧,让你不再为IP封禁烦恼了! 
本文介绍了Python爬虫应对IP封禁的策略,包括使用代理IP隐藏真实IP、选择稳定且数量充足的代理IP服务商、建立代理IP池增加爬虫效率、设置合理抓取频率以及运用验证码识别技术。这些方法能提升爬虫的稳定性和效率,降低被封禁风险。
|
2天前
|
数据采集 存储 JSON
Python爬虫面试:requests、BeautifulSoup与Scrapy详解
【4月更文挑战第19天】本文聚焦于Python爬虫面试中的核心库——requests、BeautifulSoup和Scrapy。讲解了它们的常见问题、易错点及应对策略。对于requests,强调了异常处理、代理设置和请求重试;BeautifulSoup部分提到选择器使用、动态内容处理和解析效率优化;而Scrapy则关注项目架构、数据存储和分布式爬虫。通过实例代码,帮助读者深化理解并提升面试表现。
25 0
|
2天前
|
数据采集 Web App开发 开发者
探秘Python爬虫技术:王者荣耀英雄图片爬取
探秘Python爬虫技术:王者荣耀英雄图片爬取