简体   繁体   English

如何检查响应类型 aiohttp asyncio python

[英]how to check response type aiohttp asyncio python

I have the following method:我有以下方法:

    async def make_request(self, url):
        async with aiohttp.ClientSession() as session:
            async with self.limit, session.get(url=url) as response:
                resp = await response.read()
                await asyncio.sleep(self.rate)
                return resp

How to check if resp contains json ?如何检查resp是否包含json so that I could format in json eg json.dumps(resp) perhaps?这样我就可以格式化json例如json.dumps(resp)也许? and if the resp type is html then i will have to traverse the html tree to extract the resp value如果 resp 类型是html那么我将不得不遍历 html 树来提取resp value

I have tried:我努力了:

    async def make_request(self, url):
        async with aiohttp.ClientSession() as session:
            async with self.limit, session.get(url=url) as response:
                resp = await response.json()
                await asyncio.sleep(self.rate)
                return resp

But it errors out if the resp contains html但如果resp包含html

As mentioned above checking the Content-Type header should be the first step;如上所述,检查Content-Type header 应该是第一步; however if for any reason that header is missing or is incorrect you can always use:但是,如果由于任何原因 header 丢失或不正确,您始终可以使用:

text = await response.text()
try:
    data = json.loads(text)
except ValueError as exc:
    print("cannot parse JSON: %s" % exc)
    # use text value 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM