# coding=utf-8
import time, datetime
import requests
import json
import re
from lxml import etree
# 访问芝麻IP的API链接(有则开启)
# r = requests.get("http://http.tiqu.alicdns.com/getip3?n*****************************************gions=")
# 没有API链接时开启(两者开启一即可)
r = requests.get("https://www.baidu.com/")
# 百度链接
http_url = "https://www.baidu.com/"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36"
}
# 开始时间
start =time.time()
# 希望程序运行的总时间(s)
totle_time = 600
if r.ok:
# 有api链接时开启
# proxy_ip_text = r.text
# 没有API时
proxy_ip_text = """
{"code":0,"success":true,"msg":"0","data":[{"ip":"58.218.200.220","port":9083,"expire_time":"2019-06-27 16:47:05","outip":"114.233.213.188"}]}
"""
code = json.loads(proxy_ip_text)["code"]
print(code)
if code == 0:
proxy_ip_list = json.loads(proxy_ip_text)["data"]
# print(proxy_ip_list)
ip_list = []
for proxy_ip in proxy_ip_list:
# 从API链接中获取ip和端口号
# 获取ip、端口号和类型
# ip = proxy_ip["ip"]
# port = proxy_ip["port"]
# expire_time = proxy_ip["expire_time"]
# 填入单个ip和端口号
ip = "112.65.52.102"
port = "4275"
proxy_dict = {
"https": "https://{0}:{1}".format(ip, port),
}
failure_times = 0
succeed_times = 0
total_times = 0
while True:
# 运行中访问监控
middle_time = int(time.time() - start)
print("当前用时:" + str(middle_time))
print("总访问次数是:" + str(total_times))
print("成功访问次数是:" + str(succeed_times))
print("失败访问次数是:" + str(failure_times))
if middle_time > totle_time:
print("运行时长:" + str(middle_time))
break
while True:
try:
total_times += 1
response = requests.get(http_url, proxies=proxy_dict, timeout=1.5, headers=headers)
except Exception as e:
print(e)
# 无效IP
Invalid_IP = re.findall(r"(ConnectionResetError\(10054)", str(e), re.S)
if Invalid_IP:
print("执行删除IP的操作!")
# print(e)
failure_times += 1
break
else:
res_code = response.status_code
if res_code >= 200 and res_code < 300:
succeed_times += 1
print("访问成功,effective ip! 返回的code是:" + str(res_code))
# 将有效IP存入数据库中
# some code
elif res_code == 503:
print("服务器错误,请重试!")
failure_times += 1
break
else:
print("code原因导致访问失败!code为:" + str(res_code))
failure_times += 1
break
else:
print("code不为0,获取IP失败!")
else:
print("没有获得有效的IP!")
# 程序结束时间
end = time.time()
# # 打印出程序的运行时间
print('Running time: {} Seconds'.format(end-start))
print("*"*100)
print("总访问次数是:" + str(total_times))
print("成功访问次数是:" + str(succeed_times))
print("失败访问次数是:" + str(failure_times))
print(str(middle_time)+ "s成功率:" + str(int((succeed_times/total_times)*100)) + "%")
print(str(middle_time)+ "s失败率:" + str(int((failure_times/total_times)*100)) + "%")
完毕!