文章目录

  • 概述
    • 提供免费代理的网站
  • 代码
    • 导包
    • 网站页面的url
    • ip地址
    • 检测
    • 整理
    • 必要参数
    • 总代码
  • 总结

概述

用爬虫时,大部分网站都有一定的反爬措施,有些网站会限制每个 IP 的访问速度或访问次数,超出了它的限制你的 IP 就会被封掉。对于访问速度的处理比较简单,只要间隔一段时间爬取一次就行了,避免频繁访问;而对于访问次数,就需要使用代理 IP 来帮忙了,使用多个代理 IP 轮换着去访问目标网址可以有效地解决问题。

目前网上有很多的代理服务网站提供代理服务,也提供一些免费的代理,但可用性较差,如果需求较高可以购买付费代理,可用性较好。

因此我们可以自己构建代理池,从各种代理服务网站中获取代理 IP,并检测其可用性(使用一个稳定的网址来检测,最好是自己将要爬取的网站),再保存到数据库中,需要使用的时候再调用。

提供免费代理的网站

厂商名称 地址
66代理 http://www.66ip.cn/
西刺代理 https://www.xicidaili.com
全网代理 http://www.goubanjia.com
云代理 http://www.ip3366.net
IP海 http://www.iphai.com
快代理 https://www.kuaidaili.com
免费代理IP库 http://ip.jiangxianli.com
小幻代理 https://ip.ihuan.me/

本次使用的案例是小幻代理

代码

导包

import loguru, requests, random, time  # 发送请求,记录日志,等
from lxml import etree  # 分析数据
from concurrent.futures import ThreadPoolExecutor  # 线程池

网站页面的url

由于小幻代理的每个页面的url没有规律,所以需要一一获取

def get_url():  # 得到存放ip地址的网页print("正在获取ip池", ",不要着急!")for i in range(random.randint(10, 20)):  # 爬取随机页数time.sleep(1)if i == 0:url = "https://ip.ihuan.me/"else:url = url_list[-1]try:resp = requests.get(url=url, headers=headers_test, timeout=10)except Exception as e:print(e)breakhtml = etree.HTML(resp.text)ul = html.xpath('//ul[@class="pagination"]')ul_num = html.xpath('//ul[@class="pagination"]/li')for j in range(len(ul_num)):if j != 0 and j != len(ul_num) - 1:a = ul[0].xpath(f"./li[{j}+1]/a/@href")[0]url_list.append("https://ip.ihuan.me/" + a)  # 得到许多的代理ip网址loguru.logger.info(f"over,{url}")

ip地址

def get_ip():for i in url_list:time.sleep(1)resp = requests.get(url=i, headers=headers)html = etree.HTML(resp.text)td = html.xpath("//tbody/tr")for i in td:ip = i.xpath("./td[1]//text()")[0]  # 地址pt = i.xpath("./td[2]//text()")[0]  # 端口tp = "http" if i.xpath("./td[5]//text()")[0] == "不支持" else "https"  # 访问类型ip_list.append({"type": tp, "proxy": f"{ip}:{pt}"})loguru.logger.info("ip地址获取完成")

检测

def test_ip(ip):proxy_test = {"http": f"{ip}","https": f"{ip}"# 注意:如果请求的ip是https类型的,但代理的ip是只支持http的,那么还是使用本机的ip,如果请求的ip是http类型的,那么代理的ip一定要是http的,前面不能写成https,否则使用本机IP地址}resp = requests.get(url=url_test, headers=headers, proxies=proxy_test, timeout=6)if resp.json()["origin"] == ip.split(":")[0]:ip = {"type": url.strip(":")[0], "proxy": ip}  # 格式化ip,便于后期处理,是的其有http/https标识temp_ip.append(ip)  # 符合条件的添加,不符合条件的抛弃

整理

def set_ip(url) -> "动态构建ip池":  # 要传入需要爬取网页的urltry:f = open('./app/ip.txt', "r")for j in eval(f.read()):temp_ip.append(j)f.close()except Exception as e:print("没有ip,正在构造ip池,请稍等")if not temp_ip:  # 判断是否有ip地址print("没有ip地址,正在获取")get_url()else:for i in temp_ip:ip_list.append(i)  # 将已有的ip添加到测试ip中temp_ip.clear()get_ip()  # 得到大量ip地址with open('./app/ip.txt', "w") as file:file.write(ip_list)ip_able = list(set(j["proxy"] for j in ip_list if j["type"] == url.split(":")[0]))  # 存放符合要求的ip字符串,同时利用字典去重url_test = "http://httpbin.org/ip" if url.split(":")[0] == "http" else ""  # 测试ip地址是否有用def test_ip(ip):proxy_test = {"http": f"{ip}","https": f"{ip}"# 注意:如果请求的ip是https类型的,但代理的ip是只支持http的,那么还是使用本机的ip,如果请求的ip是http类型的,那么代理的ip一定要是http的,前面不能写成https,否则使用本机IP地址}resp = requests.get(url=url_test, headers=headers, proxies=proxy_test, timeout=6)if resp.json()["origin"] == ip.split(":")[0]:ip = {"type": url.strip(":")[0], "proxy": ip}  # 格式化ip,便于后期处理,是的其有http/https标识temp_ip.append(ip)  # 符合条件的添加,不符合条件的抛弃with ThreadPoolExecutor(50) as pool:  # 使用多线程测试pool.map(test_ip, ip_able)pool.join()print("测试完毕")if temp_ip:i = random.choice(temp_ip)proxy = {"http": f"{i['proxy']}","https": f"{i['proxy']}"}return proxyelse:set_ip(url=url)

必要参数

# 参数headers = {'User-Agent': "Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 96.0.4664 .93 Safari / 537.36","Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
}
headers_test = {'User-Agent': "Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 96.0.4664 .93 Safari / 537.36","accept-encoding": "gzip, deflate, br","cookie": "Hm_lvt_8ccd0ef22095c2eebfe4cd6187dea829=1642389014,1642412091","Referer": "https://ip.ihuan.me/"
}
url_list, ip_list, temp_ip = ["https://ip.ihuan.me/"], [], []  # 存放url, 存放ip地址, 有用的ip地址

总代码

import loguru, requests, random, time
from lxml import etree
from concurrent.futures import ThreadPoolExecutordef get_url():  # 得到存放ip地址的网页print("正在获取ip池", ",不要着急!")for i in range(random.randint(10, 20)):  # 爬取随机页数time.sleep(1)if i == 0:url = "https://ip.ihuan.me/"else:url = url_list[-1]try:resp = requests.get(url=url, headers=headers_test, timeout=10)except Exception as e:print(e)breakhtml = etree.HTML(resp.text)ul = html.xpath('//ul[@class="pagination"]')ul_num = html.xpath('//ul[@class="pagination"]/li')for j in range(len(ul_num)):if j != 0 and j != len(ul_num) - 1:a = ul[0].xpath(f"./li[{j}+1]/a/@href")[0]url_list.append("https://ip.ihuan.me/" + a)  # 得到许多的代理ip网址loguru.logger.info(f"over,{url}")def get_ip():for i in url_list:time.sleep(1)resp = requests.get(url=i, headers=headers)html = etree.HTML(resp.text)td = html.xpath("//tbody/tr")for i in td:ip = i.xpath("./td[1]//text()")[0]  # 地址pt = i.xpath("./td[2]//text()")[0]  # 端口tp = "http" if i.xpath("./td[5]//text()")[0] == "不支持" else "https"  # 访问类型ip_list.append({"type": tp, "proxy": f"{ip}:{pt}"})loguru.logger.info("ip地址获取完成")def set_ip(url) -> "动态构建ip池":  # 要传入需要爬取网页的urltry:f = open('./app/ip.txt', "r")for j in eval(f.read()):temp_ip.append(j)f.close()except Exception as e:print("没有ip,正在构造ip池,请稍等")if not temp_ip:  # 判断是否有ip地址print("没有ip地址,正在获取")get_url()else:for i in temp_ip:ip_list.append(i)  # 将已有的ip添加到测试ip中temp_ip.clear()get_ip()  # 得到大量ip地址with open('./app/ip.txt', "w") as file:file.write(ip_list)ip_able = list(set(j["proxy"] for j in ip_list if j["type"] == url.split(":")[0]))  # 存放符合要求的ip字符串,同时利用集合去重url_test = "http://httpbin.org/ip" if url.split(":")[0] == "http" else ""  # 测试ip地址是否有用def test_ip(ip):proxy_test = {"http": f"{ip}","https": f"{ip}"# 注意:如果请求的ip是https类型的,但代理的ip是只支持http的,那么还是使用本机的ip,如果请求的ip是http类型的,那么代理的ip一定要是http的,前面不能写成https,否则使用本机IP地址}resp = requests.get(url=url_test, headers=headers, proxies=proxy_test, timeout=6)if resp.json()["origin"] == ip.split(":")[0]:ip = {"type": url.strip(":")[0], "proxy": ip}  # 格式化ip,便于后期处理,是的其有http/https标识temp_ip.append(ip)  # 符合条件的添加,不符合条件的抛弃with ThreadPoolExecutor(50) as pool:  # 使用多线程测试pool.map(test_ip, ip_able)pool.join()print("测试完毕")if temp_ip:i = random.choice(temp_ip)proxy = {"http": f"{i['proxy']}","https": f"{i['proxy']}"}return proxyelse:set_ip(url=url)# 参数headers = {'User-Agent': "Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 96.0.4664 .93 Safari / 537.36","Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
}
headers_test = {'User-Agent': "Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 96.0.4664 .93 Safari / 537.36","accept-encoding": "gzip, deflate, br","cookie": "Hm_lvt_8ccd0ef22095c2eebfe4cd6187dea829=1642389014,1642412091","Referer": "https://ip.ihuan.me/"
}
url_list, ip_list, temp_ip = ["https://ip.ihuan.me/"], [], []  # 存放url, 存放ip地址, 有用的ip地址if __name__ == '__main__':proxy = set_ip(url="https://www.baidu.com")  # 得到代理ipprint(proxy)

总结

如果安装了数据库的话,可以使用数据库存储得到的ip,代码中使用的是本地的文件存储数据,同时,要尽量避免本机ip被封

Python构建代理ip池相关推荐

  1. Python搭建代理IP池(一)- 获取 IP

    使用爬虫时,大部分网站都有一定的反爬措施,有些网站会限制每个 IP 的访问速度或访问次数,超出了它的限制你的 IP 就会被封掉.对于访问速度的处理比较简单,只要间隔一段时间爬取一次就行了,避免频繁访问 ...

  2. 爬虫采集自己构建代理ip池有什么优势?

    为何一些爬虫采集的专业技术人员购买了代理ip还会继续自己构建一个ip池,自己构建ip池有什么优势? (1)可无限制的调用API获取代理ip; 购买收费的代理ip,绝大多数都会提供API链接接口,客户利 ...

  3. Python搭建代理IP池(三)- 检测 IP

    在获取 IP 时,已经成功将各个网站的代理 IP 获取下来了,然后就需要一个检测模块来对所有的代理进行一轮轮的检测,检测可用就设置为满分,不可用分数就减 1,这样就可以实时改变每个代理的可用情况,在获 ...

  4. Python搭建代理IP池(二)- 存储 IP

    上一文写了如何从代理服务网站提取 IP,本文就讲解如何存储 IP,毕竟代理池还是要有一定量的 IP 数量才行.存储的方式有很多,直接一点的可以放在一个文本文件中,但操作起来不太灵活,而我选择的是 My ...

  5. Python构造代理IP池提高访问量

    1.构造代理ip池: def create_proxy_pool():# 从西拉免费ip代理网站获取代理IP列表r = requests.get('https://www.kuaidaili.com/ ...

  6. Python爬虫-代理ip池建立

    代理IP池建立 前言 之前提到过urllib和requests的利用代理ip的访问方式 . https://blog.csdn.net/zhouchen1998/article/details/813 ...

  7. NodeJs从零构建代理ip池(一)介绍

    <原文地址> 本系列主要讲解如何从零实现一个简单的代理 IP 池,教你从 Node 爬虫入门到融会贯通. 跟着本系列教程,将会学到一个完整 NodeJs 项目的开发到部署的一整套流程. 零 ...

  8. python 代理ip池_GitHub - xuan525/proxy_pool: Python爬虫代理IP池(proxy pool)

    ProxyPool 爬虫代理IP池 ______ ______ _ | ___ \_ | ___ \ | | | |_/ / \__ __ __ _ __ _ | |_/ /___ ___ | | | ...

  9. 用python代码构建代理IP池并过滤代理IP

    很多小伙伴在获得了批量的代理IP后,对IP的清洗存在疑问,这篇就叫你快速过滤代理IP import requestsdef proxy_use():# 以百度为目标urlurl = "htt ...

  10. python 爬虫工具 butter_GitHub - TheButterflyOdor/proxy_pool: Python爬虫代理IP池(proxy pool)

    爬虫IP代理池 ______ ______ _ | ___ \_ | ___ \ | | | |_/ / \__ __ __ _ __ _ | |_/ /___ ___ | | | __/| _// ...

最新文章

  1. python实现D‘Agostino‘s K-squared test正态分布检验
  2. 如何将CSS应用于iframe?
  3. 050_Boolean对象
  4. sql sum条件求和_Hive中使用over()实现累积求和和滑动求和
  5. 10774: matrix
  6. 构建二叉堆时间复杂度的证明
  7. 逗牙搞笑网www.idouya.xin
  8. android tombstone发生过程,Android Tombstone解决步骤
  9. Python 中的 while循环 和 for... in ...循环
  10. pyqt5信号与槽连接的生命周期与对象引用的生命周期
  11. win7 gho封装教程
  12. c语言自动生成uml,五个免费UML建模工具推荐
  13. Java中各种读写文件的方法
  14. 波士顿学院的计算机科学,美国波士顿学院计算机科学专业本科申请
  15. ipad显示portal服务器获取不,苹果portal认证失败原因合集
  16. Arduino - 继电器
  17. MAC-MAC-MAC-MAC
  18. Oracle中如何查询CLOB字段类型的内容
  19. 【实时渲染】实时渲染中的光与颜色
  20. NCT青少年编程能力等级测试Python编程三级-模拟卷1(含答案)

热门文章

  1. ADODB.Recordset 错误 '800a0e7d' 的解决方法
  2. 基于Easyui框架的datagrid绑定数据,新增,修改,删除方法(一)
  3. Scratch编程与科学结合-串联与并联
  4. 常用的 Cron 时间表达式 定时器 正则表达式
  5. UE4保存信息到本地
  6. java xcap_java实现发布订阅
  7. 游戏运行库java下载官网_游戏运行库合集安装包(Visual C++,Microsoft .NET,Microsoft XNA,Microsoft XML等几十种)...
  8. ML — 浅谈聚类和分类的区别
  9. 计算机图形学实验一直线-DDA算法
  10. 智能优化算法:蝙蝠算法-附代码