Python爬虫--用户代理IP池

前面一篇讲了用户 UA 代理池,现在这篇来讲下 IP 代理,

相对于 UA 来说,IP 更容易被封,

这里讲两种方法。


方法一:本地ip池

方法一 就是将 IP 拿下来本地,然后通过随机选取或者其他来调用

这就跟之前使用 UA 差不多,只不过函数不同

这里使用 urllib.request.ProxyHandler() 方法

ProxyHandler() 函数是 来设置使用代理服务器

废话不多说,先来简单的看看


import urllib.request
import random

ip_pool = [

	"192.168.0.1",
	"192.168.0.2",
	"192.168.0.3",
	"192.168.0.4",
	"192.168.0.5"

]

def IP(ip_pool):

	this_ip = random.choice(ip_pool)  #  随机选取一个

	proxy = urllib.request.ProxyHandler({"http":ip})

	opener = urllib.request.build_opener(proxy,urllib.request.HTTPHandler)

	urllib.request.install_opener(opener)

# if __name__ == '__main__':
# 	ua(ip_pool)

这样就封装好了一个函数


我们再拿 糗事百科 来举例吧

这次加一个 try except 来捕获异常


import urllib.request
import random

ip_pool = [

	"192.168.0.1",
	"192.168.0.2",
	"192.168.0.3",
	"192.168.0.4",
	"192.168.0.5"

]

def IP(ip_pool):

	this_ip = random.choice(ip_pool)  #  随机选取一个

	proxy = urllib.request.ProxyHandler({"http":this_ip})

	opener = urllib.request.build_opener(proxy,urllib.request.HTTPHandler)

	urllib.request.install_opener(opener)

for i in range(1,5):

	try:
		IP(ip_pool)

		this_url = "https://www.qiushibaike.com/text/page/"+str(i)+"/"

		data = urllib.request.urlopen(this_url).read().decode("utf-8","ignore")

		path = '<div class="content">.*?<span>(.*?)</span>.*?</div>'

		resut = re.compile(path,re.S).findall(data)

		for j in resut:
			print(j)
			
		time.sleep(0.5)

	except Exception as error:
		print(error)

这样就可以了,即使那个 ip 访问不了,也不会影响到程序的执行


方法二:IP接口

第二种方法就是调用 IP 接口了

有些网站提供 ip 池,然后只需要调用他那个接口就行了

这里简单提一下,可能不同网站调用方法不同


import urllib.request
import random

def IP(ip_pool):

	this_ip = urllib.request.urlopen("http://www.xxx.com/?xxx=xxx")  #  调用接口提取 ip

	proxy = urllib.request.ProxyHandle({"http":this_ip})

	opener = urllib.request.build_opener(proxy,urllib.request.HTTPHandler)

	opener = urllib.request.build_opener(proxy,urllib.request.HTTPHandler)

	urllib.request.install_opener(opener)


for i in range(1,5):

	try:
		IP(ip_pool)

		this_url = "https://www.qiushibaike.com/text/page/"+str(i)+"/"

		data = urllib.request.urlopen(this_url).read().decode("utf-8","ignore")

		path = '<div class="content">.*?<span>(.*?)</span>.*?</div>'

		resut = re.compile(path,re.S).findall(data)

		for j in resut:
			print(j)
			
		time.sleep(0.5)

	except Exception as error:
		print(error)
  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

余十步

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值