python爬取快代理IP并测试IP的可用性

用到的网站https://www.kuaidaili.com/,免费的IP很不稳定,随时会挂,有需求的还是购买付费IP比较稳

import requests
from urllib import parse
from bs4 import BeautifulSoup

headers={
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'
}

session=requests.session()
session.headers=headers

# 获取IP地址页面
def getIP(url):
    html=requests.get(url)
    # print(html.status_code)
    # print(html.text)
    if html.status_code==200:
        html.encoding=html.apparent_encoding
        soup=BeautifulSoup(html.text,'lxml')
        trs=soup.select('tbody tr')
        for tr in trs:
            ip=tr.select('td')[0].text
            port=tr.select('td')[1].text
            type=tr.select('td')[3].text
            TestIP(ip,port,type)

# 测试IP代理的可用性,并将可用IP写入文件
def TestIP(ip,port,type):
    url="https://www.baidu.com"
    proxies={
        'http':'{}://{}:{}'.format(type,ip,port),
        'https':'{}://{}:{}'.format(type,ip,port)
    }
    # print(proxies)
    try:
        re=session.get(url,proxies=proxies,timeout=2,verify=False)
        print(re.status_code)
        print("可用IP为{}://{}:{}".format(type,ip,port))
        f.write("{}://{}:{}\n".format(type,ip,port))    # 写入文件
    except:
        print("不可用IP为{}://{}:{}".format(type,ip,port))

if __name__ == '__main__':
    t=input("请输入要爬取的页数,每页15个:")
    url1="https://www.kuaidaili.com/free/intr/"
    with open('IP代理.txt','w') as f:
        for i in range(int(t)):
            url=parse.urljoin(url1,str(i+1))
            print(url)
            getIP(url)

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员班长

感谢您的一路相伴

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值