我有以下方法。
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
这样我就可以用格式化 json
如 json.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
如上所述,检查 Content-Type
头部应该是第一步;但是如果因为任何原因该头部缺失或不正确,你可以随时使用。
text = await response.text()
try:
data = json.loads(text)
except ValueError as exc:
print("cannot parse JSON: %s" % exc)
# use text value