快速构建一个免费的IP代理池

2023-11-18

文章使用的代理ip链接为:

云代理: http://www.ip3366.net/?stype=1&page=1

验证IP网站为: http://'http://httpbin.org/ip

get方式请求进去,要设置好请求头,cookie

self.faker = Faker(locale='zh_CN')
        self.headers = {
            'User-Agent': self.faker.chrome(),
            'Cookie':'Hm_lvt_c4dd741ab3585e047d56cf99ebbbe102=1667027823,1668068804; Hm_lpvt_c4dd741ab3585e047d56cf99ebbbe102=1668068825',
            'Host':'www.ip3366.net',
        }

 这里的UA我是使用faker伪造的,当然这也没什么,只是为了让浏览器知道你是一个用户

请求成功后,用xpath来获取ip地址和端口号

将获取到的IP地址和端口号放到列表中

num = int(input('输入爬取页数: '))
        self.ip_list = []
        for page in range(num):
            print(f"==============================正在爬取第{page+1}页==============================")
            self.url = f'http://www.ip3366.net/?stype=1&page={page+1}'
            reqs = requests.get(self.url, headers=self.header)
            reqs.encoding = 'gb2312'
            selecotors = Selector(reqs.text)
            tr_lists = selecotors.xpath('//div[@id="container"]/div[@id="list"]/table[@class="table table-bordered table-striped"]/tbody/tr')
            item = {}
            for tr_list in tr_lists:
                item['ip_dz'] = tr_list.xpath('./td[1]/text()').get()
                item['prots'] = tr_list.xpath('./td[2]/text()').get()
                # item['type_s'] = tr_list.xpath('./td[4]/text()').get()
                self.proxys = {
                    'http': item['ip_dz']+ ':'+item['prots'],
                    'https': item['ip_dz']+ ':'+item['prots']
                }
                print(self.proxys)
                self.ip_list.append(self.proxys)

进行IP验证,设置超时时间为6,超过为不可用,找到可用IP

        can_ip = []
        cant_ip = []
        for ip in self.ip_list:
            try:
                req = requests.get(url='http://httpbin.org/ip', headers=self.headers, proxies=ip, timeout=6)
                # print(req.json())
                req_json = req.json()
                req_ip = req_json.get('origin')
                print('这是origin: ',req_ip)
                http_ip_prot = ip.get('http')
                http_ip = re.search(r'(.*?):(\d+)', http_ip_prot, re.S).group(1)
                print('这是http_ip: ', http_ip)
                try:
                    if req.status_code == 200 and http_ip==req_ip:
                        can_ip.append(ip)
                        print(ip, '可用')
                        print(req.json())
                    else:
                        cant_ip.append(ip)
                        print(ip, '不可用')
                except:
                    cant_ip.append(ip)
                    print(ip, '不可用')
            except:
                cant_ip.append(ip)
                print(ip, '不可用')

将可用IP保存为csv文件

        with open('IP_use.csv', 'w', encoding='utf-8', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(can_ip)

这里展示全部代码:

import requests
# import time
from faker import Faker
from parsel import Selector
import csv
import re




class IPDL():
    def __init__(self):
        self.faker = Faker(locale='zh_CN')
        self.header = {
            'User-Agent': self.faker.chrome(),
            'Cookie':'Hm_lvt_c4dd741ab3585e047d56cf99ebbbe102=1674180209; Hm_lpvt_c4dd741ab3585e047d56cf99ebbbe102=1674184681',
            'Host':'www.ip3366.net',
        }


    def get_html(self):
        num = int(input('输入爬取页数: '))
        self.ip_list = []
        for page in range(num):
            print(f"==============================正在爬取第{page+1}页==============================")
            self.url = f'http://www.ip3366.net/?stype=1&page={page+1}'
            reqs = requests.get(self.url, headers=self.header)
            reqs.encoding = 'gb2312'
            selecotors = Selector(reqs.text)
            tr_lists = selecotors.xpath('//div[@id="container"]/div[@id="list"]/table[@class="table table-bordered table-striped"]/tbody/tr')
            item = {}
            for tr_list in tr_lists:
                item['ip_dz'] = tr_list.xpath('./td[1]/text()').get()
                item['prots'] = tr_list.xpath('./td[2]/text()').get()
                # item['type_s'] = tr_list.xpath('./td[4]/text()').get()
                self.proxys = {
                    'http': item['ip_dz']+ ':'+item['prots'],
                    'https': item['ip_dz']+ ':'+item['prots']
                }
                print(self.proxys)
                self.ip_list.append(self.proxys)

    def train_ip(self):
        """检测ip的函数"""
        self.headers = {
            'User-Agent': self.faker.chrome(),
        }
        can_ip = []
        cant_ip = []
        for ip in self.ip_list:
            try:
                req = requests.get(url='http://httpbin.org/ip', headers=self.headers, proxies=ip, timeout=6)
                # print(req.json())
                req_json = req.json()
                req_ip = req_json.get('origin')
                print('这是origin: ',req_ip)
                http_ip_prot = ip.get('http')
                http_ip = re.search(r'(.*?):(\d+)', http_ip_prot, re.S).group(1)
                print('这是http_ip: ', http_ip)
                try:
                    if req.status_code == 200 and http_ip==req_ip:
                        can_ip.append(ip)
                        print(ip, '可用')
                        print(req.json())
                    else:
                        cant_ip.append(ip)
                        print(ip, '不可用')
                except:
                    cant_ip.append(ip)
                    print(ip, '不可用')
            except:
                cant_ip.append(ip)
                print(ip, '不可用')


        with open('IP_use.csv', 'w', encoding='utf-8', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(can_ip)


        print('可用ip共:',len(can_ip))
        print('不可用ip共:',len(cant_ip))


    def mains(self):
        self.get_html()
        # self.save()
        self.train_ip()

if __name__ == '__main__':
    IPDL().mains()

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

快速构建一个免费的IP代理池 的相关文章

随机推荐

  • vscode配置快捷键注释模板

    文章目录 前言 一 打开配置项 1 首选项编辑配置 2 新建代码片段 3 配置注释文件名 二 新建代码注释模板 三 注释使用 前言 本篇文章可以在vscode中配置快捷键显示代码的信息注释 如作者 描述 创建时间等 一 打开配置项 1 首选
  • SD卡中FAT32文件格式快速入门(图文详细介绍)

    说明 MBR Master Boot Record 主引导记录 DBR DOS Boot Record 引导扇区 FAT File Allocation Table 文件分配表 硬件 本文SD卡为Kingston 4GB FAT32格式 簇
  • 【Python】 Pandas数据导入与导出

    数据读取 import pandas as pd data pd read csv data csv 读取数据文件 print data 数据索引与查看 x data loc x 读取表头为 x 的那一列的数据 print x y data
  • 如何自学现代计算机科学(转)

    简介 这里收集了很多学习资源 都是关于一些适合本科生学习的计算机科学 话题 Topics 这里仅仅只提供 话题 列表 而不会提供诸如知识点剖析 练习题等内容 如果你对某一个话题特别感兴趣 想深入研究一下 但又买不起文中提到的书籍 实体书 那
  • 使用docker搭建FastDFS文件系统

    使用docker搭建FastDFS文件系统 1 拉取fastdfs镜像 docker search fastdfs 这里要选择 delron fastdfs 镜像 docker pull delron fastdfs 2 启动容器 2 1
  • 车祸相关公开数据集(免费下载)

    Vehicle Collisions 纽约市机动车与人相撞 背景描述 这是 2021 年在纽约发生的人与机动车碰撞事故的数据 仅过滤掉超过 1 000 美元的受伤或死亡案件 总结了事件的日期和时间 受伤的位置以及警方对事件的描述 数据说明
  • Dubbo源码分析-Spring与Dubbo整合原理与源码分析(二)

    Spring与Dubbo整合的整体流程 基于apache dubbo 2 7 15 因为dubbo有较多的兼容以前的代码比如 DubboReference 以前就有两个版本 Reference 和 com alibaba dubbo con
  • list 分组_学习笔记系列_10_数据聚合与分组操作

    开篇导包 一 数据聚合 df groupby 详解 DataFrame 参数 by 用作分组的条件对象 mapping function label or list of labels axis 轴方向 0 or index 1 or co
  • Golang笔记:UDP基础使用与广播

    文章目录 目的 基础说明 作为服务器使用 作为客户端使用 广播 总结 目的 UDP是比较基础常用的网络通讯方式 这篇文章将介绍Go语言中UDP基础使用的一些内容 本文中使用 Packet Sender 工具进行测试 其官网地址如下 http
  • 大数据常见错误解决方案(转载)

    1 用 bin spark shell启动spark时遇到异常 java net BindException Can t assign requested address Service sparkDriver failed after 1
  • java代理

    静态代理 import java util logging Level import java util logging Logger 定义接口 代理类和被代理类都要实现这个接口 interface IHello public void h
  • KALI中Arping的使用方法(2023)

    一 介绍 ARP协议是 Address Resolution Protocol 地址解析协议 的缩写 在同一以太网中 通过地址解析协议 源主机可以通过目的主机的IP地址获得目的主机的MAC地址 arping程序就是完成上述过程的程序 arp
  • 【YOLOv5-6.x】解决加入CA注意力机制不显示FLOPs的问题

    1 问题描述 问题源自之前写的一篇博客 魔改YOLOv5 6 x 中 加入ACON激活函数 CBAM和CA注意力机制 加权双向特征金字塔BiFPN 尝试在YOLOv5的backbone中加入Coordinate Attention 虽然加入
  • 程序员应了解的那些事(5)C++迭代器之iterator_traits/iterator_category

    lt 1 gt traits 所谓traits 可以理解为 萃取机 作用就是 你丢给他什么东西 他会给你拿出你想要的特性 迭代器的特性 iterator traits lt gt lt 2 gt 迭代器的属性迭代器是沟通算法和容器的桥梁 一
  • 小程序获取链接中的参数

    onLoad function options if options null options undefined options sharetype null options sharetype gt 0 console log opti
  • 【Android入门到项目实战-- 7.3】—— 如何调用手机摄像头和相册

    目录 一 调用摄像头拍照 二 打开相册选择照片 学完本篇文章可以收获如何调用手机的摄像头和打开手机相册选择图片功能 一 调用摄像头拍照 先新建一个CameraAlbumTest项目 修改activity main xml 代码如下 按钮打开
  • 零基础学习hadoop到上手工作线路指导(不断更新)

    本帖最后由 pig2 于 2014 2 23 10 22 编辑 零基础学习hadoop 没有想象的那么困难 也没有想象的那么容易 在刚接触云计算 曾经想过培训 但是培训机构的选择就让我很纠结 所以索性就自己学习了 整个过程整理一下 给大家参
  • python处理excel数据

    文章目录 前言 一 用到的模块是什么 二 execl表格的样式 三 模块的使用 1 引入模块 2 读取excel表数据 3 将写入excel表 四 代码分析 1 代码逻辑 2 选出有用的股票号并与回报率关联 3 将全部数据按照所需要的股票号
  • safari无法打开网页是什么原因?mac上的Safari浏览器打不开网页怎么办?

    只要是MacOS系统的都会附带一个Safari浏览器 完美兼容Mac PC 及 iPod touch iPhone iPad 功能和性能自然是不错的 但是也会出现如safari浏览器无法打开网页的情况 那么safari无法打开网页是什么原因
  • 快速构建一个免费的IP代理池

    文章使用的代理ip链接为 云代理 http www ip3366 net stype 1 page 1 验证IP网站为 http http httpbin org ip get方式请求进去 要设置好请求头 cookie self faker