如何检查响应类型 aiohttp asyncio python

问题描述 投票:1回答:1

我有以下方法。

    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

如何检查 resp 包含 json这样我就可以用格式化 jsonjson.dumps(resp) 如果resp类型是 html 然后,我将不得不遍历html树来提取的 resp value

我已经试过了。

    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

但如果有以下情况就会出错 resp 包含 html

python python-asyncio semaphore aiohttp
1个回答
1
投票

如上所述,检查 Content-Type 头部应该是第一步;但是如果因为任何原因该头部缺失或不正确,你可以随时使用。

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

© www.soinside.com 2019 - 2024. All rights reserved.