有的时候,希望能够爬取一些外网的数据,但是开启Clash
之类的软件后,发现会直接报requests.exceptions.ProxyError
的错误。解决方法的代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import requests import urllib3
urllib3.disable_warnings()
url = "https://www.google.com"
proxies = { 'http': 'http://127.0.0.1:7890/', 'https': 'http://127.0.0.1:7890/' }
response = requests.get(url=url, verify=False, proxies=proxies)
PYTHON
|
将代理的IP地址以及端口号写死的做法并不优雅,可以使用
urllib.request
中的
getproxies
获取系统Web代理信息。当未开启代理时,返回空字典,开启代理时,返回如下的字典:
1 2 3 4 5
| { 'http': 'http: 'https': 'https: 'ftp': 'ftp: }
JSON
|
urllib3.disable_warnings()
这样的代码也不够优雅。使用
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") )
PYTHON
|
也可以使用
Client
,和
requests
的
session
基本一致
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
|