获取代理ip访问指定网站并记录访问速度,成功率,真实访问ip
import json from selenium import webdriver import requests class A(): def __init__(self): self.url = 'yoururl' def get_prosy_ip(self): response = requests.post(self.url) print(response) text = response.text # 拿到代理ip port = text.split(':')[-1].split('}')[0] ip = text.split(':')[-2].split('"')[1] proxy_ip = 'socks5://{}:{}'.format(ip, port) return proxy_ip def prosy_amazon(self, proxy_ip): # 使用代理访问amazon chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--proxy-server=%s' % proxy_ip) chrome = webdriver.Chrome(options=chrome_options) chrome.get("https://www.amazon.com") chrome.set_script_timeout(10) chrome.set_page_load_timeout(10) mes = chrome.execute_script('return JSON.stringify(window.performance.timing)') connect_start = mes.split(':')[2].split(',')[0] connect_end = mes.split(':')[3].split(',')[0] amazon_link_time = (int(connect_end)) - (int(connect_start)) chrome.quit() json_time = json.dumps(amazon_link_time) with open('unittest4.txt', 'a') as f: f.write("amazon_link_time:") f.write(json_time) # print(mes) def truth_ip(self, proxy_ip): # 查看真实访问ip chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--proxy-server=%s' % proxy_ip) chrome = webdriver.Chrome(options=chrome_options) chrome.get("https://api.myip.com") chrome.set_script_timeout(10) chrome.set_page_load_timeout(10) mes2 = chrome.find_element_by_xpath('/html/body').text truth_ip = mes2.split(':')[1].split(',')[0] truth_country = mes2.split(':')[-2].split(',')[0] json_mes2 = json.dumps(truth_ip) json_mes3 = json.dumps(truth_country) mes1 = chrome.execute_script('return JSON.stringify(window.performance.timing)') connect_start = mes1.split(':')[2].split(',')[0] connect_end = mes1.split(':')[3].split(',')[0] tip_link_time = (int(connect_end)) - (int(connect_start)) chrome.quit() json_time1 = json.dumps(tip_link_time) with open('unittest4.txt', 'a') as f: f.write("tip_link_time:") f.write(json_time1) f.write("truth_ip:") f.write(json_mes2) f.write("truth_country:") f.write(json_mes3) f.write("\n") print(mes1) def start(self): proxy_ip = self.get_prosy_ip() while True: self.prosy_amazon(proxy_ip) self.truth_ip(proxy_ip) if __name__ == "__main__": # dore = A() # dore.start() try: doer = A() doer.start() except Exception as e: print(str(e)) with open('unittest4.txt', 'a') as f: f.write('error:') f.write(str(e)) doer = A() doer.start()
处理json格式文件我不会 只会用split和with open这种
欢迎大神指点
第一次用selenium测试记录 day:2021.11.23