python通过免费代理构建可用代理池-简单示例

以下为简单示例,后续再进行优化,特作记录!

import requests
import re
import telnetlib

url='http://www.66ip.cn/nmtq.php?getnum=100000&isp=0&anonymoustype=4&start=&ports=&export=&ipaddress=&area=2&proxytype=0&api=66ip'
header = {
    
    'User-agent':'xxxxxxxxxxx','Connection':'close'}
page_text = requests.get(url=url,headers=header).text
#用于匹配ip:port的正则表达式
p = r'(?:((?:\d|[1-9]\d|1\d{2}|2[0-5][0-5])\.(?:\d|[1-9]\d|1\d{2}|2[0-5][0-5])\.(?:\d|[1-9]\d|1\d{2}|2[0-5][0-5])\.(?:\d|[1-9]\d|1\d{2}|2[0-5][0-5]))\D+?(6[0-5]{2}[0-3][0-5]|[1-5]\d{4}|[1-9]\d{1,3}|[0-9]))'
#匹配出所有的ip与端口,放入列表
iplist = re.findall(p,page_text)
# 判断爬取的代理ip是否可用
for i in iplist:
    ip = i[0]+':'+i[1]+'\n'
    try:
        # 使用代理ip访问指定网站,能访问说明代理可用
        # requests.get('http://www.baidu.com', proxies={"http": ip})
        # 使用telnet测试代理是否可用
        telnetlib.Telnet(i[0], port=i[1], timeout=3)
    except:
        print('connect failed')
    else:
        print(ip)
        with open('ip.txt', 'a+', encoding='utf-8') as fp:
            fp.write(ip)

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42380348/article/details/122832448