[英]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.