python爬虫时,判断IP代理是否有效的解决方法

1、不停的请求测试,可以发现网络IP在不断更新 

import requests
import random
# 该网站会返回你请求网站时的IP地址信息
url = 'http://icanhazip.com'
#首先我们在xicidaili.com中获取一些ip代理信息,放入列表中
proxies_list = [
		'http://117.66.167.116:8118',
		'http://118.190.95.35:9001',
		'http://116.77.204.2:80',
		'http://110.40.13.5:80'
	]
# ip_list是后续我们用来更新列表用的,保存真实可用的IP信息
ip_list = []

flag = 1
while True:	
	proxy_ip = random.choice(proxies_list)
	proxies = {'http': proxy_ip}
	try:
        # 如果请求成功,证明这个ip代理是可用的,我们不修改flag的值
		wb_data = requests.get(url=url,proxies=proxies)
	except:
        # 如果请求失败,我们从列表中删除指定的内容选项
		proxies_list.remove(proxies['http'])
		# 并将flag值置为0
		flag = 0
    # 之后我们根据flag的值来判断这个IP地址是否是有效的,这样可以不断地测试。
	if flag == 1:
		ip_list.append(proxies['http'])
		print (ip_list)

2、我们遍历一次所有的IP地址,输出可用的IP地址组成的列表

import requests
url = 'http://icanhazip.com'
proxies_list = [
		'http://117.66.167.116:8118',
		'http://118.190.95.35:9001',
		'http://116.77.204.2:80',
		'http://110.40.13.5:80'
	]
ip_list = []

for proxy_ip in proxies_list:
	print (proxy_ip)
	# print(proxies_list)
	proxies = {'http': proxy_ip}
	try:
		wb_data = requests.get(url=url,proxies=proxies)
		flag = True
	except:
		proxies_list.remove(proxies['http'])
		flag = False

	if flag:
		ip_list.append(proxies['http'])
print (ip_list)

如果有需要请自行获取其他的IP地址,进行调试

猜你喜欢

转载自blog.csdn.net/qq_32670879/article/details/83302216