使用aiohttp库设置代理抓取https页面报错问题解决
有一次通过aiohttp库设置代理抓取https页面报错,错误如下:aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host www.phper163.com:443 ssl:default [参数错误。]不加代理的话,抓取https页面是正常的import asyncioimport aiohttpdef mai
·
有一次通过aiohttp库设置代理抓取https页面报错,错误如下:
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host www.phper163.com:443 ssl:default [参数错误。]
不加代理的话,抓取https页面是正常的
import asyncio
import aiohttp
def main():
loop=asyncio.get_event_loop()
url='https://www.phper163.com/getIP.php'
con = aiohttp.TCPConnector(ssl=False)
async with aiohttp.ClientSession(connector=con, trust_env=True) as session:
async with session.get(url,timeout=30,proxy='http://61.151.202.84:4002') as resp:
print(resp.status)
asyncio.run(main())
执行上面代码会报错,如果不设置 proxy='http://61.151.202.84:4002',则能正常请求数据。
通过搜索得知,添加下面一段代码即可
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
最终代码如下:
import asyncio
import aiohttp
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) # 加上这一行,解决使用代理请求 https会报错问题
async def main():
loop=asyncio.get_event_loop()
url='https://www.phper163.com/getIP.php'
con = aiohttp.TCPConnector(ssl=False)
async with aiohttp.ClientSession(connector=con, trust_env=True) as session:
async with session.get(url,timeout=30,proxy='http://61.151.202.84:4002') as resp:
print(resp.status)
asyncio.run(main())
更多推荐
已为社区贡献1条内容
所有评论(0)