python爬取代理IP并保存到本地

在爬虫项目中,代理IP的作用是很重要的,在爬取网站数据的时候IP经常被封,所以经常需要更换IP;花钱买吧,对于咱们这种用来测试的来说有点划不来,所以只能找一些免费的用,今天跟大家介绍一个免费代理IP的网站:https://www.kuaidaili.com/

爬取很简单,静态网站,我就不啰嗦了,直接上代码:

import requests
import parsel


def get_ip(page):
    target = f'https://www.kuaidaili.com/free/inha/{page}/'

    headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3760.400 QQBrowser/10.5.4083.400',
    }
    html = requests.get(target,headers=headers).text
    res = parsel.Selector(html)

    for each in res.xpath('//*[@id="list"]/table/tbody/tr'):
    	# 匹配 IP 
        ip = each.xpath('./td/text()').get()
        # 匹配 端口号
        port = each.xpath('./td[2]/text()').get()
        
        # 将IP和端口号连接
        ip_port = 'http://'+ ip + ":" + port
        # print(ip_port)

        proxies = {'http': ip_port}
       
        try:
            test = requests.get('https://www.taobao.com/', timeout=0.1, proxies=proxies)
            # 测试 IP 是否可用
            if test.status_code == 200:
                print('响应成功:',ip_port)
                with open('./images/ip池.txt',"a",encoding='utf-8') as f:
                    f.write(ip_port)
                    f.write("\n")
        except:
            print('响应失败!')
            continue

if __name__ == "__main__":
    for page in range(1,11):
        get_ip(page)

try里面是用来测试IP是否可用的,设置响应时间为0.1秒,如可用则保存进本地,否则,PASS,够简单吧!

在这里插入图片描述

运气还不错,免费的居然还有这么多可以用的

在这里插入图片描述
爬了10页,有98个可以用的,各位去试一下吧!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值