高效Python爬虫:多进程与异步抓取思路

目录

  1. 🔹 多进程
    • 使用场景
    • 进程池应用
    • 多进程有序抓取
    • 多进程无序抓取
    • 多进程爬虫操作实践
  2. 🔹 异步抓取
    • 异步阻塞和非阻塞
    • 异步抓取应用场景
    • 异步关键字和aiohttp
    • 异步抓取百万数据思路

多进程

🔹 多进程使用场景

多进程适用于CPU密集型任务,例如数据处理、复杂计算等。对于爬虫来说,当网络I/O操作较多时,多进程可以有效提高抓取速度。


🔹 进程池应用

使用multiprocessing库的Pool类来管理进程池,提高资源利用率。

python 复制代码
from multiprocessing import Pool
import os

def worker(num):
    print(f"Worker {num} in process {os.getpid()}")

if __name__ == "__main__":
    with Pool(4) as pool:
        pool.map(worker, range(10))

🔹 在这个示例中,我们创建了一个包含4个进程的进程池,并使用map方法将任务分配给进程池中的进程。


🔹 多进程有序抓取

有序抓取确保抓取结果按照任务分配顺序返回。

python 复制代码
from multiprocessing import Pool
import requests

def fetch(url):
    response = requests.get(url)
    return response.text

if __name__ == "__main__":
    urls = ['http://example.com/page1', 'http://example.com/page2', 'http://example.com/page3']
    with Pool(4) as pool:
        results = pool.map(fetch, urls)
    for content in results:
        print(content[:100])

🔹 使用map方法保证结果按顺序返回。


🔹 多进程无序抓取

无序抓取不保证任务结果的返回顺序。

python 复制代码
from multiprocessing import Pool
import requests

def fetch(url):
    response = requests.get(url)
    return response.text

if __name__ == "__main__":
    urls = ['http://example.com/page1', 'http://example.com/page2', 'http://example.com/page3']
    with Pool(4) as pool:
        results = pool.imap_unordered(fetch, urls)
    for content in results:
        print(content[:100])

🔹 使用imap_unordered方法不保证返回顺序。


🔹 多进程爬虫操作实践

综合应用多进程技术进行爬虫操作。

python 复制代码
from multiprocessing import Pool
import requests
from bs4 import BeautifulSoup

def fetch(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    return soup.title.string

if __name__ == "__main__":
    urls = ['http://example.com/page1', 'http://example.com/page2', 'http://example.com/page3']
    with Pool(4) as pool:
        titles = pool.map(fetch, urls)
    for title in titles:
        print(title)

🔹 在这个示例中,我们使用多进程并行抓取网页数据,并提取每个网页的标题。


异步抓取

🔹 异步阻塞和非阻塞

异步编程可以显著提高I/O密集型任务的性能。阻塞意味着等待操作完成,非阻塞则立即返回继续执行。

python 复制代码
import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

asyncio.run(main())

🔹 这个简单示例展示了如何使用异步编程等待1秒钟。


🔹 异步抓取应用场景

异步适用于大量网络I/O操作,例如大规模网页抓取。


🔹 异步关键字和aiohttp

使用asyncawait关键字与aiohttp库进行异步抓取。

python 复制代码
import aiohttp
import asyncio

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main():
    urls = ['http://example.com/page1', 'http://example.com/page2', 'http://example.com/page3']
    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, url) for url in urls]
        results = await asyncio.gather(*tasks)
    for content in results:
        print(content[:100])

asyncio.run(main())

🔹 使用aiohttp进行异步HTTP请求,可以显著提高抓取速度。


🔹 异步抓取百万数据思路

抓取大量数据时,可以分批次进行,提高稳定性。

python 复制代码
import aiohttp
import asyncio

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def batch_fetch(urls):
    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, url) for url in urls]
        return await asyncio.gather(*tasks)

async def main():
    base_url = 'http://example.com/page'
    all_urls = [f"{base_url}{i}" for i in range(1, 1000001)]
    batch_size = 1000
    for i in range(0, len(all_urls), batch_size):
        batch_urls = all_urls[i:i + batch_size]
        results = await batch_fetch(batch_urls)
        for content in results:
            print(content[:100])

asyncio.run(main())

🔹 通过分批次抓取,我们可以更高效、更稳定地处理大量数据抓取任务。


总结

🔹 通过本次学习,我们深入了解了多进程和异步编程在Python爬虫中的应用,包括多进程的使用场景、进程池应用、有序与无序抓取、多进程爬虫操作实践,以及异步编程的阻塞与非阻塞、异步抓取应用场景、关键字和aiohttp库的使用,以及异步抓取百万数据的思路。

🔹 掌握这些技术后,我们可以更高效地进行大规模网页数据抓取,为数据分析和处理提供坚实的基础。希望这些内容能够帮助大家更好地理解和应用多进程与异步编程,提高爬虫抓取效率!🚀

相关推荐
吴天德少侠22 分钟前
c++返回一个pair类型
开发语言·c++
ok!ko1 小时前
设计模式之工厂模式(通俗易懂--代码辅助理解【Java版】)
java·开发语言·设计模式
学地理的小胖砸1 小时前
【GEE的Python API】
大数据·开发语言·前端·python·遥感·地图学·地理信息科学
尘心cx1 小时前
抽象类介绍
python
刘好念1 小时前
[Python]使用python统计docx文档字符、单词数
python·office
qq_317060952 小时前
java之http client工具类
java·开发语言·http
天启代理ip2 小时前
HTTP隧道代理:互联网冲浪的隐形翅膀
服务器·网络·爬虫·网络协议·tcp/ip
robot_大菜鸟2 小时前
python_openCV_计算图片中的区域的黑色比例
开发语言·python·opencv
AI让世界更懂你3 小时前
漫谈设计模式 [18]:策略模式
python·设计模式·策略模式
Pandaconda3 小时前
【C++ 面试 - 新特性】每日 3 题(六)
开发语言·c++·经验分享·笔记·后端·面试·职场和发展