import requests
# 使用代理IP进行请求的示例代码
def fetch_with_proxy(url, proxy):
try:
# 设置代理
proxies = {
'http': proxy,
'https': proxy,
}
# 发送请求
response = requests.get(url, proxies=proxies, timeout=5)
# 检查响应状态码
if response.status_code == 200:
print("请求成功")
return response.text
else:
print(f"请求失败,状态码: {response.status_code}")
return None
except Exception as e:
print(f"请求过程中出现错误: {e}")
return None
# 示例代理IP和目标URL
proxy_ip = "http://123.45.67.89:8080"
target_url = "http://httpbin.org/ip"
# 调用函数
result = fetch_with_proxy(target_url, proxy_ip)
if result:
print("返回内容:", result)
else:
print("未获取到内容")
fetch_with_proxy函数:该函数接收两个参数,一个是目标URL,另一个是代理IP。proxies字典设置HTTP和HTTPS请求的代理。requests.get方法发送GET请求,并传递代理配置。fetch_with_proxy函数并打印结果。希望这段代码对你有帮助!
上一篇:python删除文件夹
下一篇:python 格式化字符串
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站