在Python中设置代理IP可以通过使用`requests`或`urllib`库来实现。以下是使用`requests`库设置代理IP的示例代码:
```python
import requests
设置代理IP
proxies = {
'http': 'http://代理IP:端口',
'https': 'https://代理IP:端口'
}
发送请求时使用代理IP
response = requests.get('https://www.example.com', proxies=proxies)
打印响应内容
print(response.text)
如果代理IP需要身份验证,可以在代理URL中添加用户名和密码:
```python
import requests
设置代理IP,包含用户名和密码
proxies = {
'http': 'http://用户名:密码@代理IP:端口',
'https': 'https://用户名:密码@代理IP:端口'
}
发送请求时使用代理IP
response = requests.get('https://www.example.com', proxies=proxies)
打印响应内容
print(response.text)
使用`urllib`库设置代理IP的示例代码如下:
```python
import urllib.request
创建代理处理器
proxy_handler = urllib.request.ProxyHandler({
'http': 'http://代理IP:端口',
'https': 'https://代理IP:端口'
})
创建opener
opener = urllib.request.build_opener(proxy_handler)
安装opener
urllib.request.install_opener(opener)
发送请求
response = urllib.request.urlopen('http://目标网址')
读取响应内容
print(response.read().decode('utf-8'))
请确保将`代理IP`、`端口`、`用户名`、`密码`和`目标网址`替换为实际的值。