当前位置:   article > 正文

python之爬虫异步请求asyncio、aiohttp库用法_asyncio和aiohttp库来实现图片的异步post请求

asyncio和aiohttp库来实现图片的异步post请求

一、Post请求

import asyncio
import aiohttp
import time
import json

class Win:
    async def post_request(self,session,t):
    	await asyncio.sleep(0.3)     # 协程使用的延时功能
        print(t)
        url = 'https://ug.baidu.com/mcp/pc/pcsearch'
        data = {"invoke_info":{"pos_1":[{}],"pos_2":[{}],"pos_3":[{}]}}
        headers = {
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
        }
        # proxy = 'http://143.25.222.12:50003'     # 使用代理ip时打开
        proxy = None
        try:
            async with session.post(url=url,headers=headers,data=json.dumps(data),proxy=proxy) as response:
                if response.status == 200:
                    text = await response.text()
                    print("Success",text)
        except aiohttp.ClientError as e:
            print("Error:", e)
    async def run(self,t):
        async with aiohttp.ClientSession() as session:
            tasks = []
            for i in range(1):
                task = asyncio.ensure_future(self.post_request(session,t))
                tasks.append(task)
            await asyncio.gather(*tasks)

    def main(self):
        loop = asyncio.get_event_loop()
        t = time.time()
        loop.run_until_complete(self.run(t))
        print(time.time() - t)


if __name__ == "__main__":
    a = Win()
    a.main()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

二、Get请求

类似于requests的get,使用和上面差不多(params,allow_redirects都能用),代理使用参考上面post请求用proxy。

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号