如何在python中使用代理示例
import requests
# 请求地址 简单提取 具体需要根据实际情况获取 记得添加白名单 一般白名单添加后,10秒左右才生效
api = '' # 这里填写你购买后生成的API网址,如果没有或者不会,请找客服 如:http://www.soyunip.com/api?ddbh=s8349453653
try:
txt = requests.get(api, timeout=10) # 请求API网址,返回代理IP 超时设置的是10秒
txt.raise_for_status() # 如果响应状态码不是200,引发异常
ip = txt.text.strip() # 返回的内容如:125.26.21.154:13456
# 如果返回是多行多个代理信息的,需要解析一下
a = ip.split('\r\n') # 这里返回多行多个代理IP,默认是以\r\n分隔符的
if len(a) > 0:
myip = a[0] # 这里取第一个代理IP 实际应用时,根据需要自己选择
else:
raise ValueError("No valid IP address found in response")
# 代理服务器
ipport = "http://" + myip
# 如果有设置代理账号和密码
# ipport = f'http://代理ip的账号:代理ip的密码@{myip}'
# 下面举例是你要访问的网站链接
url = "http://myip.ipip.net"
proxies = {
'http': ipport,
'https': ipport
}
headers = {} # 根据自己业务逻辑填写头信息,这部分可以省略
res = requests.get(url, proxies=proxies, headers=headers)
res.raise_for_status() # 如果响应状态码不是200,引发异常
print(res.text) # 打印返回的内容
except requests.RequestException as e:
print(f"An error occurred: {e}")