测试爬取IP是否可用代码

import random
import requests

file = open('use_ip.txt', 'w', encoding='utf-8')
with open(r'E:\python练习\爬虫\ip.txt', 'r', encoding='UTF-8') as f:
    for line in f.readlines():
        thisProxy = line.split(",")[3].lower() + "://" + line.split(",")[0] + ":" + line.split(",")[1]
        try:
            requests.adapters.DEFAULT_RETRIES = 3
            res = requests.get(url="http://icanhazip.com/", timeout=8, proxies={"http": thisProxy})
            proxyIP = thisProxy
            if proxyIP == thisProxy:
                print("代理IP:'" + proxyIP + "'有效!")
                file.write(proxyIP + "\n")
            else:
                print("代理IP无效!")
        except:
            print("代理IP无效!")

猜你喜欢

转载自blog.csdn.net/zcb_data/article/details/109393781