• 4.24aiohttp模块学习


    下载:pip install aiohttp

    案例练习:爬取优美图库图片

    # requests.get() 同步的代码 -> 异步操作aiohttp
    # pip install aiohttp
    
    import asyncio
    import aiohttp
    
    urls = [
        "http://kr.shanghai-jiuxin.com/file/2020/1031/191468637cab2f0206f7d1d9b175ac81.jpg",
        "https://d1icd6shlvmxi6.cloudfront.net/gsc/9YL27B/dc/fe/9c/dcfe9cd3c23641dc82aa8a15b44f7caa/images/login/u10.png?token=2800dd9468999f997788328d3f28019bfe1fcab8057c1d57e742ed0c32e45928",
        "http://kr.shanghai-jiuxin.com/file/2020/1031/774218be86d832f359637ab120eba52d.jpg"
    ]
    
    
    async def aiodownload(url):
        # 发送请求.
        # 得到图片内容
        # 保存到文件
        name = url.rsplit("/", 1)[1]  # 从右边切, 切一次. 得到[1]位置的内容
        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, "搞定")
    
    
    async def main():
        tasks = []
        for url in urls:
            tasks.append(aiodownload(url))
    
        await asyncio.wait(tasks)
    
    
    if __name__ == '__main__':
        asyncio.run(main())
  • 相关阅读:
    PHP面向对象
    PHP正则表达式
    PHP数组
    PHP常用函数
    PHP自定义函数与字符串处理
    PHP函数
    PHP语句
    WAMP环境配置
    Bootstrap输入框组
    Bootstrap按钮组嵌套、垂直排列、两端对齐
  • 原文地址:https://www.cnblogs.com/zhaoyids/p/14903858.html
Copyright © 2020-2023  润新知