原始代码:
import httpx
import asyncio
async def main():
url = 'http://api.bilibili.com/x/web-interface/view?aid=170001'
async with httpx.AsyncClient() as client:
resp = await client.get(url)
if resp.status_code == 200:
data = resp.json()
print(data)
else:
print(f'Request failed with status code: {resp.status_code}')
if __name__ == '__main__':
asyncio.run(main())
运行结果:
Request failed with status code: 307
排查了两小时也没发现哪里出问题了,尝试加过useragent,完成请求头,最后咨询网友才知道是http的问题,只需要将http改成https即可正常返回结果😑
修复后的代码:
import httpx
import asyncio
async def main():
url = 'https://api.bilibili.com/x/web-interface/view?aid=170001'
async with httpx.AsyncClient() as client:
resp = await client.get(url)
if resp.status_code == 200:
data = resp.json()
print(data)
else:
print(f'Request failed with status code: {resp.status_code}')
if __name__ == '__main__':
asyncio.run(main())