Python爬虫优雅地自动启用代理

之前有提到过如何使用 Python + Clash,爬取外网数据,然而这样写并不够优雅:

  1. 代理的IP地址以及端口号是固定的、写死的
  2. 含有urllib3.disable_warnings()这样不优雅的代码

GetProxies

urllib.request中的getproxies可以轻松的获取系统Web代理信息。当未开启代理时,返回空字典,开启代理时,返回如下的字典

1
2
3
4
5
{
'http': 'http://127.0.0.1:7890',
'https': 'https://127.0.0.1:7890',
'ftp': 'ftp://127.0.0.1:7890'
}

HTTPX

使用httpx则不用设置urllib3.disable_warnings()verify=False

1
2
3
4
5
6
7
8
from urllib.request import getproxies
import httpx


response = httpx.get(
"https://www.google.com/",
proxy=getproxies().get("http")
)

也可以使用Client,和requestssession基本一致

1
2
3
4
5
6
7
8
9
from urllib.request import getproxies
import httpx


client = httpx.Client(
proxy=getproxies().get("http")
)

response = client.get("https://www.google.com/")

Python爬虫优雅地自动启用代理
https://zuoguan.netlify.app/2024/04/13/Python爬虫优雅地自动启用代理/
作者
坐观是只皮卡丘
发布于
2024年4月13日
许可协议