设置单个代理ip 和多个代理ip的request

本文介绍如何在Python中使用urllib.request模块设置单个和多个代理IP进行网络爬虫,解决IP被封或限制的问题。通过示例代码展示了代理处理器和自定义opener的创建过程。

下面我们来介绍一下设置单个代理ip 和多个代理ip的request
书写爬虫程序的时候,经常会会遇到ip被封的问题,或者说ip被限制的问题,那么就需要用到ip代理了,那么ip代理在request里面的原理究竟是怎么实现的呢?下面来了解一下。
单个ip设置代理
import urllib.request

def create_handler():
url = ‘http://httpbin.org/ip’
# 添加代理
proxy = {
# ‘http’: ‘http://119.5.72.6:4226’ # 这是官方定义的
‘http’: ‘119.5.72.6:4226’
}
# 代理处理器
proxy_handler = urllib.request.ProxyHandler(proxy)
# 创建自己的opener
opener = urllib.request.build_opener(proxy_handler)
# 拿着代理ip去发送请求
data = opener.open(url).read()
print(data)

if name == ‘main’:
create_handler()
12345678910111213141516171819
多个ip设置代理
import urllib.request

def proxy_handel():
proxy_list = [
{‘http’: ‘125.111.149.163:4205’},
{‘http’: ‘106.46.136.93:4225’},
{‘http’: ‘114.230.18.38:4228’},
{‘http’: ‘115.151.50.141:4273’},
{‘http’: ‘182.105.201.153:4275’},
]
for proxy in proxy_list:
print(proxy)
# 创造处理器
proxy_head = urllib.request.ProxyHandler(proxy)
# 创建opener
opener = urllib.request.build_opener(proxy_head)

    try:
        print(opener.open('http://httpbin.org/ip', timeout=1).read())
        print('=='*20)
    except Exception as e:
        print(e)

if name == ‘main’:
proxy_handel()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值