python配置代理
时间: 2023-11-20 17:51:26 浏览: 35
Python提供了多种方法来配置代理,以下是其中两种常用的方法:
1. 使用requests库设置代理IP
可以使用requests库来设置代理IP,具体代码如下:
```
import requests
proxies = {
"http": "http://127.0.0.1:8888",
"https": "http://127.0.0.1:8888",
}
response = requests.get("http://www.baidu.com", proxies=proxies)
print(response.text)
```
其中,proxies字典中的键为协议类型,值为代理IP地址和端口号。
2. 使用urllib库设置代理IP
可以使用urllib库来设置代理IP,具体代码如下:
```
import urllib.request
proxy_ip = "http://127.0.0.1:8888"
proxy_handler = urllib.request.ProxyHandler({"http": proxy_ip})
opener = urllib.request.build_opener(proxy_handler)
response = opener.open("http://www.baidu.com")
print(response.read().decode("utf-8"))
```
其中,ProxyHandler类用于处理代理信息,build_opener方法用于构造自定义的opener对象,使用自定义的opener对象发起访问请求。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)