首页 > 其他分享 >asyncio + httpx异步请求板子

asyncio + httpx异步请求板子

时间:2024-08-27 14:14:29浏览次数:7  
标签:异步 url json result file async httpx asyncio

AI 写的 asyncio + httpx 异步请求板子

import asyncio
import httpx
import json
import aiofiles
from pathlib import Path
project_dir = Path(__file__).resolve().parent

# 使用代理
proxy = "http://username:password@ip:port"
# 异步并发数
max_concurrency = 5
input_file_name = '任务名单'
exit_file_name = '已采集名单'
output_file_name = '已采集名单'


also = set()
# 剔除已经采集过的任务
with open(project_dir.joinpath(exit_file_name), 'r', encoding='utf-8') as f:
    for line in f:
        try:
            doc = json.loads(line.strip())
            _id = doc.get("_id")
            also.add(_id)
        except:
            pass

tasks = []
with open(project_dir.joinpath(input_file_name), 'r', encoding='utf-8') as f:
    for line in f:
        if line.strip() in also:
            continue
        tasks.append(line.strip())


async def fetch_url(session, task, headers, cookies, retries=3, backoff_factor=0.5):
    """
    异步获取指定 URL 的内容,最多重试指定次数。
    """

    # 构造一下url
    url = f"https://{task}.com"

    for attempt in range(retries):
        try:
            response = await session.get(url, headers=headers, cookies=cookies)
            if response.status_code == 200:
                doc = response.json()
                # 一种异常响应处理
                if doc.get('code') == 1000000:
                    print(f"【error】{task}")
                    return {}

                # 返回正常响应
                else:
                    return response.json()
            else:
                print(f"Attempt {attempt + 1}: Unexpected status code {response.status_code} for {url}")
        except httpx.RequestError as exc:
            print(f"Attempt {attempt + 1}: Request failed for {task}: {exc}")

        # 如果不是最后一次重试,则等待一段时间后再重试
        if attempt < retries - 1:
            await asyncio.sleep(backoff_factor * (2 ** attempt))  # 指数退避

    # 所有重试都失败时,返回空字典
    print(f"Failed to fetch {url} after {retries} attempts.")
    return {}

async def write_json_to_file(data):
    """
    异步写入 JSON 数据到文件。
    """
    async with aiofiles.open(project_dir.joinpath(output_file_name), 'a+', encoding='utf-8') as file:
        await file.write(json.dumps(data, ensure_ascii=False) + '\n')

async def main(urls, max_concurrency=5, proxy=None):
    """
    异步执行多个 URL 的请求。
    """
    headers = {
        "accept": "*/*",
        "accept-language": "zh-CN,zh;q=0.9",
        "cache-control": "no-cache",
        "content-type": "application/json",
        "pragma": "no-cache",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36"
    }
    cookies = {

    }
    async with httpx.AsyncClient(proxies=proxy) as client:
        semaphore = asyncio.Semaphore(max_concurrency)

        async def fetch_with_semaphore(url):
            async with semaphore:
                result = await fetch_url(client, url, headers, cookies)
                # 可保存的结果,这里写一段parser
                if result and result.get("message", "") == "Success" and result.get("data", {}):
                    ret = result
                    await write_json_to_file(ret)
                elif result:
                    print(result)
                return result

        tasks = [fetch_with_semaphore(url) for url in urls]
        await asyncio.gather(*tasks)

asyncio.run(main(tasks, max_concurrency, proxy=proxy))

标签:异步,url,json,result,file,async,httpx,asyncio
From: https://www.cnblogs.com/thx2199/p/18382611

相关文章

  • 【项目实践】CompletableFuture异步编排在多任务并行执行中的使用
    【项目实践】CompletableFuture异步编排在多任务并行执行中的使用一、单次请求处理多任务的场景        在实际项目中,我们经常会遇到一些比较复杂的查询,需要给前端响应一个内容量较大的响应结果。例如在租房系统的app中,点击具体的某个房间查看详情,需要后端将这个房间的......
  • Linux异步通知
    1.异步通知简介我们首先来回顾一下“中断”,中断是处理器提供的一种异步机制,我们配置好中断以后就可以让处理器去处理其他的事情了,当中断发生以后会触发我们事先设置好的中断服务函数,在中断服务函数中做具体的处理。信号类似于我们硬件上使用的“中断”,只不过信号是软......
  • 【python】Python中小巧的异步web框架Sanic快速上手实战
    ✨✨欢迎大家来到景天科技苑✨✨......
  • 九、前端中的异步方法Promise,Promise详解
    文章目录1.Promise简介什么是promise为什么使用Promisepromise中的状态2.Promis的用法1.Promise简介什么是promisePromise是异步编程的一种解决方案,它的构造函数是同步执行的,then方法是异步执行的。为什么使用Promise在JavaScript的世界中,所有代码都是单线程执......
  • 直播系统开发,接口异步调用一小步,耗时减少一大步
    直播系统开发,接口异步调用一小步,耗时减少一大步随着直播系统开发业务发展,底层数据量越来越大,业务逻辑也日趋复杂化,某些接口耗时也越来越长,这时候接口就需要进行性能优化了,当然性能优化主要跟业务相关涉及改造点可能各不相同,这里就来介绍异步调用多个接口减少响应时间。适用......
  • 直播电商源码,用异步加成打造更高性能
    直播电商源码,用异步加成打造更高性能单线程和异步js是单线程语言,同时只能做一件事浏览器和node已支持js启动进程,如WebWorkerjs和DOM渲染共用同一个线程,因为js可修改DOM结构遇到等待(网络请求,定时任务)不能卡住,所以需要异步同步会阻塞代码执行,异步不会阻塞代码......
  • lua协程实现异步编程模式
    异步编程模式只是一个代码结构,c#中的async/await的写法就是异步编程模式,这边就是通过协程来达到和async/await类似的效果。 异步编程模式写法1:资源分帧加载这边运行环境用的是:Unity+xLua lua脚本:Assets/Lua/Test9.lua.txtlocal_Time=CS.UnityEngine.Timelocalfunct......
  • Android开发 - Looper 类处理异步任务和消息解析
    什么是LooperLooper是一个非常重要的概念,它与线程、消息队列和处理异步任务密切相关。是Android中用于管理线程的消息循环的类。它与线程中的MessageQueue结合工作,用于处理异步任务和消息Looper的主要概念消息队列(MessageQueue)一个用于存放要处理的消息和任务的队......
  • 记一次vue数据异步刷新引发的bug
    问题背景在开发过程中,为了threejs对象在watch监听中能够被顺利取到,我加了一个信号量,在初始化对象后,通过threejs对象状态和表单状态来重新渲染画面。然而,我把threejs对象从null设置为正常的对象时,页面居然卡死了。在实际的代码中,用到对象的情况只有wacth里面监听到信号量为true时......
  • 消息队列作用(解耦、异步、削峰)
    原文:消息队列作用(解耦、异步、削峰)图详解一、消息队列简介简单来说,“消息队列”是在消息的传输过程中保存消息的容器。MQ全称为MessageQueue,消息队列(MQ)是一种应用程序对应用程序的通信方法。应用程序通过读写出入队列的消息(针对应用程序的数据)来通信。消息传递指的是程......