python协程爬小说

协程(coroutine)是一种比线程更轻量级的并发执行单位,他们允许函数在执行过程中阻塞暂停,,并在需要的时候恢复执行,,从而实现协作式多任务处理,,跟传统的线程不同,协程不需要依赖操作系统的调度,,因为始终都在一个线程里,,里面有一个 event_loop 去监测哪一部分需要阻塞,,一但阻塞,就切换到不被阻塞的代码执行,,

通过 await 进行挂起和恢复,,,异步IO


xpath获取页面内容

py 复制代码
from lxml import etree
etree.xpath(...)

开启协程:

py 复制代码
asyncio.run(方法名)

# 或者
 # 事件轮询 监测函数
  event_loop = asyncio.get_event_loop()
  event_loop.run_until_complete(main())

协程函数,都有一个关键字async

py 复制代码
async def mian():
	# 创建任务  asyncio.create_task(...)
	 
	# 等待所有任务执行完成. ,,, done:已经完成的任务,,是一个set对象,无序的,, 通过t.result()返回协程任务的返回值,,如果想要是有序的,使用gather函数
	done,pending = await asyncio.wait(tasks)

	# gather会直接返回有序的数组,一般return_exception设置为True,遇到错误会返回在数组中,,如果设置为False,遇到错误会抛错,代码无法执行
	result = await asyncio.gather(*task,return_exception=True)

协程发送请求和存文件:

py 复制代码
import aiohttp
import aiofiles

# aiohttp发送请求 和 requests类似
async with aiohttp.ClientSession() as session:
              async with session.get(href) as resp:
              # aiohttp设置编码
                  page_source = await resp.text(encoding="gbk")

async with aiofiles.open(f"./hehe/{title}.txt",mode="w",encoding="utf-8") as f:
                        await f.write(content)

如果文件写入失败,重试请求:

代码:

py 复制代码
import asyncio

import aiofiles
import aiohttp
import requests
from lxml import etree

def get_href_list():
    resp = requests.get("https://www.biquge635.com/mingchaonaxieshier/")
    resp.encoding = "gbk"
    href_list = etree.HTML(resp.text).xpath("//div[@class='section-box']/ul/li/a/@href")
    print(href_list)
    return href_list


async def download_one(href):
    print("开始下载%s"%href)
    while 1:
        try:
            # aio 异步io
            async with aiohttp.ClientSession() as session:
                async with session.get(href) as resp:
                    page_source = await resp.text(encoding="gbk")
                    # print(page_source)
                    tree = etree.HTML(page_source)
                    title = tree.xpath("//h1[@class='title']/text()")[0].strip()
                    content = tree.xpath("//div[@id='content']/text()")

                    content = "\n".join(content).replace("\u3000", "")
                    async with aiofiles.open(f"./hehe/{title}.txt", mode="w", encoding="utf-8") as f:
                        await f.write(content)
                        break

        except:
            print("重试%s"%href)

    print("下载结束%s" % href)
async def download(href_list):
    tasks = []
    for href in href_list:
        tasks.append(asyncio.create_task(download_one(href)))
    await asyncio.wait(tasks)

def main():
    href_list = get_href_list()

    # 启动协程
    asyncio.run(download(href_list))


if __name__ == '__main__':
    main()
相关推荐
m0_59136473几秒前
C#怎么使用LINQ OrderBy排序 C#如何用LINQ对集合按多个字段进行升序降序排列【语法】
jvm·数据库·python
m0_733565461 分钟前
HTML函数开发需要独立显卡吗_HTML函数与显卡关系详解【说明】
jvm·数据库·python
2401_884454153 分钟前
Python测试代码如何实现自解释_使用pytest描述性命名规范
jvm·数据库·python
小侯不躺平.4 分钟前
C++ Boost库【4】 --分词器的使用
c++·windows·microsoft
AI人工智能+电脑小能手8 分钟前
【大白话说Java面试题 第49题】【JVM篇】第9题:什么是双亲委派机制?介绍一下运作过程。?
java·开发语言·jvm
码农-阿杰10 分钟前
Java 线程中断机制深度解析:从 API 到底层 C++ 实现
java·开发语言·c++
Brilliantwxx12 分钟前
【C++】priority_queue以及 仿函数 的学习
开发语言·c++·笔记·学习·算法
dinglu1030DL12 分钟前
Go语言怎么格式化时间_Go语言time.Format教程【详解】
jvm·数据库·python
m0_6245785916 分钟前
SQL数据分析如何剔除极端异常值_配合窗口函数检测偏离度
jvm·数据库·python
码农学院19 分钟前
itextsharp .net中如何设置两个表格的间距设为0,取网站的域名,协议、端口、当前站点目录的地址
开发语言·c#·.net