Python异步爬虫如何使用https代理?
aiohttp 库直接使用 https 代理会报错,用 http 代理没有问题。
可是~爬虫抓取的网站需要 https,这个要怎么解决呢?
Python异步爬虫如何使用https代理?
3 回复
import aiohttp
import asyncio
async def fetch_with_proxy(url, proxy_url):
# 创建连接器并配置代理
connector = aiohttp.TCPConnector(ssl=False) # 如果代理服务器证书有问题可以关闭SSL验证
timeout = aiohttp.ClientTimeout(total=10)
async with aiohttp.ClientSession(
connector=connector,
timeout=timeout
) as session:
# 使用代理发起请求
async with session.get(url, proxy=proxy_url) as response:
return await response.text()
async def main():
# 代理格式:http://user:pass@host:port 或 https://host:port
proxy_url = "https://your-proxy-host:port" # 替换为你的HTTPS代理地址
# 如果需要认证
# proxy_url = "https://username:password@proxy-host:port"
url = "https://httpbin.org/ip" # 测试网站,返回你的IP地址
try:
html = await fetch_with_proxy(url, proxy_url)
print("请求成功,返回内容:")
print(html[:500]) # 只打印前500字符
except aiohttp.ClientError as e:
print(f"请求失败: {e}")
except asyncio.TimeoutError:
print("请求超时")
# 运行异步函数
if __name__ == "__main__":
asyncio.run(main())
关键点:
- 在
session.get()中直接传入proxy参数 - HTTPS代理地址格式为
https://host:port或带认证的https://user:pass@host:port - 如果代理服务器证书有问题,可以在
TCPConnector中设置ssl=False(生产环境慎用)
代理设置一句话建议:确保代理地址格式正确且代理服务可用。
用 http 代理可以爬 https 的内容的吧
- 忽略 ssl 验证 [doc]( https://docs.aiohttp.org/en/stable/client_reference.html?highlight=verify_ssl)
2. 代理协议使用 http/socks4/socks5

