Python爬虫 教程:IP池的使用

article/2025/10/24 4:05:29

一、简介

爬虫中为什么需要使用代理

一些网站会有相应的反爬虫措施,例如很多网站会检测某一段时间某个IP的访问次数,如果访问频率太快以至于看起来不像正常访客,它可能就会禁止这个IP的访问。所以我们需要设置一些代理IP,每隔一段时间换一个代理IP,就算IP被禁止,依然可以换个IP继续爬取。

代理的分类:

  • 正向代理:代理客户端获取数据。正向代理是为了保护客户端防止被追究责任。

  • 反向代理:代理服务器提供数据。反向代理是为了保护服务器或负责负载均衡。

免费代理ip提供网站

  • http://www.goubanjia.com/

  • 西刺代理

  • 快代理

匿名度:

  • 透明:知道是代理ip,也会知道你的真实ip

  • 匿名:知道是代理ip,不会知道你的真实ip

  • 高匿:不知道是代理ip,不会知道你的真实ip

类型:

  • http:只能请求http开头的url

  • https:只能请求https开头的url

示例

import requestsheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'
}
url = 'https://www.baidu.com/s?wd=ip'# 不同的代理IP,代理ip的类型必须和请求url的协议头保持一致
proxy_list = [{"http": "112.115.57.20:3128"},        {'http': '121.41.171.223:3128'}
]# 随机获取代理IP
proxy = random.choice(proxy_list)page_text = requests.get(url=url,headers=headers,proxies=proxy).textwith open('ip.html','w',encoding='utf-8') as fp:fp.write(page_text)print('over!')

二、IP池

1、免费IP池

从西刺代理上面爬取IP,迭代测试能否使用,建立一个自己的代理IP池,随时更新用来抓取网站数据

在这里插入图片描述

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import requests
from lxml import etree
import time
import random
from fake_useragent import UserAgentclass GetProxyIP(object):def __init__(self):self.url = 'https://www.xicidaili.com/nn/'self.proxies = {'http': 'http://163.204.247.219:9999','https': 'http://163.204.247.219:9999'}# 随机生成User-Agentdef get_random_ua(self):ua = UserAgent()        # 创建User-Agent对象useragent = ua.randomreturn useragent# 从西刺代理网站上获取随机的代理IPdef get_ip_file(self, url):headers = {'User-Agent': self.get_random_ua()}html = requests.get(url=url, proxies=self.proxies, headers=headers, timeout=5).content.decode('utf-8', 'ignore')parse_html = etree.HTML(html)        tr_list = parse_html.xpath('//tr')              # 基准xpath,匹配每个代理IP的节点对象列表for tr in tr_list[1:]:ip = tr.xpath('./td[2]/text()')[0]port = tr.xpath('./td[3]/text()')[0]            self.test_proxy_ip(ip, port)                # 测试ip:port是否可用# 测试抓取的代理IP是否可用def test_proxy_ip(self, ip, port):proxies = {'http': 'http://{}:{}'.format(ip, port),'https': 'https://{}:{}'.format(ip, port), }test_url = 'http://www.baidu.com/'try:res = requests.get(url=test_url, proxies=proxies, timeout=8)if res.status_code == 200:print(ip, ":", port, 'Success')with open('proxies.txt', 'a') as f:f.write(ip + ':' + port + '\n')except Exception as e:print(ip, port, 'Failed')def main(self):for i in range(1, 1001):url = self.url.format(i)self.get_ip_file(url)time.sleep(random.randint(5, 10))if __name__ == '__main__':spider = GetProxyIP()spider.main()

从IP池中取IP,也就是在爬虫程序中从文件随机获取代理IP

import random
import requestsclass BaiduSpider(object):def __init__(self):self.url = 'http://www.baidu.com/'self.headers = {'User-Agent': 'Mozilla/5.0'}self.flag = 1def get_proxies(self):with open('proxies.txt', 'r') as f:result = f.readlines()                  # 读取所有行并返回列表proxy_ip = random.choice(result)[:-1]       # 获取了所有代理IPL = proxy_ip.split(':')proxy_ip = {'http': 'http://{}:{}'.format(L[0], L[1]),'https': 'https://{}:{}'.format(L[0], L[1])}return proxy_ipdef get_html(self):proxies = self.get_proxies()if self.flag <= 3:try:html = requests.get(url=self.url, proxies=proxies, headers=self.headers, timeout=5).textprint(html)except Exception as e:print('Retry')self.flag += 1self.get_html()if __name__ == '__main__':spider = BaiduSpider()spider.get_html()

2.收费代理API

写一个获取收费开放API代理的接口

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import requests
from fake_useragent import UserAgentua = UserAgent()                        # 创建User-Agent对象
useragent = ua.random
headers = {'User-Agent': useragent}def ip_test(ip):url = 'http://www.baidu.com/'ip_port = ip.split(':')proxies = {'http': 'http://{}:{}'.format(ip_port[0], ip_port[1]),'https': 'https://{}:{}'.format(ip_port[0], ip_port[1]),}res = requests.get(url=url, headers=headers, proxies=proxies, timeout=5)if res.status_code == 200:return Trueelse:return False# 提取代理IP
def get_ip_list():# 快代理:https://www.kuaidaili.com/doc/product/dps/api_url = 'http://dev.kdlapi.com/api/getproxy/?orderid=946562662041898&num=100&protocol=1&method=2&an_an=1&an_ha=1&sep=2'html = requests.get(api_url).content.decode('utf-8', 'ignore')ip_port_list = html.split('\n')for ip in ip_port_list:with open('proxy_ip.txt', 'a') as f:if ip_test(ip):f.write(ip + '\n')if __name__ == '__main__':get_ip_list()

3.私密代理

1、语法结构

用户名和密码会在给API_URL的时候给。不是自己的账号和账号密码。

proxies = {
'协议':'协议://用户名:密码@IP:端口号'
}
proxies = {'http':'http://用户名:密码@IP:端口号','https':'https://用户名:密码@IP:端口号'
}
proxies = {'http': 'http://309435365:szayclhp@106.75.71.140:16816','https':'https://309435365:szayclhp@106.75.71.140:16816',
}

获取开放代理的接口

import requests
from fake_useragent import UserAgentua = UserAgent()  # 创建User-Agent对象
useragent = ua.random
headers = {'User-Agent': useragent}def ip_test(ip):url = 'https://blog.csdn.net/qq_34218078/article/details/90901602/'ip_port = ip.split(':')proxies = {'http': 'http://1786088386:b95djiha@{}:{}'.format(ip_port[0], ip_port[1]),'https': 'http://1786088386:b95djiha@{}:{}'.format(ip_port[0], ip_port[1]),}res = requests.get(url=url, headers=headers, proxies=proxies, timeout=5)if res.status_code == 200:print("OK")return Trueelse:print(res.status_code)print("错误")return False# 提取代理IP
def get_ip_list():# 快代理:https://www.kuaidaili.com/doc/product/dps/api_url = 'http://dps.kdlapi.com/api/getdps/?orderid=986603271748760&num=1000&signature=z4a5b2rpt062iejd6h7wvox16si0f7ct&pt=1&sep=2'html = requests.get(api_url).content.decode('utf-8', 'ignore')ip_port_list = html.split('\n')for ip in ip_port_list:with open('proxy_ip.txt', 'a') as f:if ip_test(ip):f.write(ip + '\n')if __name__ == '__main__':get_ip_list()

思路:

  • 写一个类;
  • get_ip() requests请求接口,得到ip和port;
  • test_ip()请求某一网站,根据状态码或in判断是否有某一内容来判断此ip是否可用,返回Ture和False即可;
  • save_ip()测试成功后保存;

http://chatgpt.dhexx.cn/article/uQMVcKin.shtml

相关文章

如何建立爬虫代理ip池

目录 一、为什么需要建立爬虫代理ip池 二、如何建立一个爬虫代理ip池 原文地址&#xff1a;https://www.cnblogs.com/TurboWay/p/8172246.html 一、为什么需要建立爬虫代理ip池 在众多的网站防爬措施中&#xff0c;有一种是根据ip的访问频率进行限制的&#xff0c;在…

requests模块代理IP池搭建视频爬取

requests模块&代理IP池搭建 一 requests模块使用1.1 get请求1.2 url编码和解码1.3 携带请求头1.4 携带cookie1.5 发送post请求1.6 requests.session1.7 Response1.8 获取二进制数据1.9 解析json 二 使用代理三 django后端获取客户端ip地址四 爬取视频网站五 爬取新闻六 Bau…

Python之爬虫 搭建代理ip池

文章目录 前言一、User-Agent二、发送请求三、解析数据四、构建ip代理池&#xff0c;检测ip是否可用五、完整代码总结 前言 在使用爬虫的时候&#xff0c;很多网站都有一定的反爬措施&#xff0c;甚至在爬取大量的数据或者频繁地访问该网站多次时还可能面临ip被禁&#xff0c;…

如何构建一个自己的代理ip池

一、默认自动切换IP 登录线程IP池客户端时&#xff0c;默认情况下会自动切换IP。 如果不想自动切换IP&#xff0c;或者还没有准备开始使用&#xff0c;请在客户端右侧将“在IP过期前几秒自动申请切换”设置为“0”。 0无效。 二.默认情况下不需要授权 默认情况下&#xff0c…

搭建代理IP池

目录 爬取前的准备 爬取有IP内容 检查IP的可用性 上一期讲到在爬取豆瓣电影Top250时&#xff0c;出现ip被封的情况&#xff0c;解决方案给出了两种&#xff1a; 1. 换个WiFi或者热点&#xff1b; 2. 搭建代理IP池。 那么这期就来搭建代理IP池。通常来说&#xff0c;搭建代理…

python搭建ip池

在爬取网站的时候我们有时候会遭受封ip等显现&#xff0c;因此我们需要搭建自己的ip池用于爬虫。 代码过程简述&#xff1a; 1、爬取代理ip网站信息 2、将获取的信息处理得到ip等关键信息 3、保存首次获取的ip信息并检测其是否可用 4、检测完毕将可用ip保存&#xff0c;搭…

搭建免费代理IP池

&#x1f468;‍&#x1f4bb;博客主页&#xff1a;i新木优子&#x1f440; &#x1f389;欢迎关注&#x1f50d;点赞&#x1f44d;收藏⭐留言&#x1f4dd; &#x1f9da;‍♂️寄语:成功的秘诀就是每天都比别人多努力一点&#x1f463; ✨有任何疑问欢迎评论探讨 先声明一下&…

python搭建ip池(多线程)

之前有讲过怎么搭建ip池&#xff0c;但由于单线程的效率太低&#xff0c;于是我们升级改造一下&#xff0c;将单线程变成多线程来搭建ip池&#xff0c;之前的方法可以参考一下&#xff1a;python搭建ip池 &#xff08;如果会简单的request和提取文字就可以直接不看&#xff09;…

教你自己搭建一个IP池(绝对超好用!!!!)

随着我们爬虫的速度越来越快&#xff0c;很多时候&#xff0c;有人发现&#xff0c;数据爬不了啦&#xff0c;打印出来一看。 不返回数据&#xff0c;而且还甩一句话 是不是很熟悉啊&#xff1f; 要想想看&#xff0c;人是怎么访问网站的&#xff1f; 发请求&#xff0c;对…

Python爬虫实战(二):爬取快代理构建代理IP池

目录 &#x1f339;前言构建IP池的目的爬取目标准备工作代码分析第一步第二步第三步第四步第五步完整代码使用方法 &#x1f339;前言 博主开始更新爬虫实战教程了&#xff0c;期待你的关注&#xff01;&#xff01;&#xff01; 第一篇&#xff1a;Python爬虫实战&#xff08;…

ERROR 1062 (23000): Duplicate entry '%-root' for key 'PRIMARY'

MySQL> update user set host% where user root; ERROR 1062 (23000): Duplicate entry %-root for key PRIMARY 然后查看了下数据库的host信息如下&#xff1a; host已经有了%这个值&#xff0c;所以直接运行命令&#xff1a; 复制代码 代码如下: MySQL>flush priv…

Mysql 报错 ERROR 1062 (23000): Duplicate entry ‘%-root‘ for key ‘PRIMARY‘

文章目录 错误详情错误原因解决方案最后 错误详情 今天在云主机上配置Hive时&#xff0c;设置远程连接的权限报错如下&#xff1a; 错误原因 之前电脑上已经有了%&#xff0c; 解决方案 查看一下电脑中是否已经具有% select host,user from user where userroot;如果已经存…

ORA-20000

exec dbms_stats.gather_database_stats(ESTIMATE_PERCENT>100, method_opt > FOR ALL INDEXED COLUMNS SIZE AUTO, cascade>true, degree>120);在12c和19c中&#xff0c;想要启用资源管理&#xff0c;必须先把并发收集统计信息禁用。 alter system set resource_…

mysql一张表复制到另外一张表,报错[23000][1062] Duplicate entry ‘1‘ for key ‘big_2.PRIMARY‘

mysql一张表复制到另外一张表 insert into big_2 select * from big_4 报错 [23000][1062] Duplicate entry 1 for key big_2.PRIMARY 看报错&#xff0c;是big_2的主键已经有1了&#xff0c;不能再插入相同的值&#xff0c;我这边id是自增字段&#xff0c;指定插入字段就能解决…

我32岁,花23000元从雕刻员转行程序员,承诺保底6K,选IT是成功了吧

我从22岁起&#xff0c;就开始在县城一家雕刻厂做流水线工人&#xff0c;从厂房门口看过去&#xff0c;雕刻厂的一切都是灰色的&#xff0c;到处落满花岗岩的灰屑。 一边是师傅们趴在石料上无休止地劳作&#xff0c;一边是新安装的数控雕刻机发出尖刻的响声&#xff0c;我是这…

Mysql出现问题:ERROR 1451 (23000): Cannot delete or updatea parent row: a foreign key constraint fail解决方案

回城传送–》《数据库问题解决方案》 ❤️作者主页:小虚竹 ❤️作者简介:大家好,我是小虚竹。Java领域优质创作者🏆,CSDN博客专家🏆,华为云享专家🏆,掘金年度人气作者🏆,阿里云专家博主🏆,51CTO专家博主🏆 ❤️技术活,该赏 ❤️点赞 👍 收藏 ⭐再看,养成…

Mysql出现问题:ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails解决方案

回城传送–》《数据库问题解决方案》 ❤️作者主页:小虚竹 ❤️作者简介:大家好,我是小虚竹。Java领域优质创作者🏆,CSDN博客专家🏆,华为云享专家🏆,掘金年度人气作者🏆,阿里云专家博主🏆,51CTO专家博主🏆 ❤️技术活,该赏 ❤️点赞 👍 收藏 ⭐再看,养成…

[23000][1452] Cannot add or update a child row: a foreign key constraint fails (`test2`.`#sql-1238_5

在建立外键关系时&#xff0c;出现该报错信息&#xff1a; [23000][1452] Cannot add or update a child row: a foreign key constraint fails (test2.#sql-1238_50, CONSTRAINT fk_student_ID FOREIGN KEY (ID) REFERENCES achievement (ID)) 原因&#xff1a; 建立外键时&a…

函数批量插入报错ERROR 1062 (23000): Duplicate entry ‘x‘ for key ‘y.PRIMARY‘

问题 测试时候发现&#xff0c;如果直接执行Insert语句是完全没有问题的&#xff0c;但是一旦使用mysql函数对insert语句中的主键做1操作&#xff0c;就开始ERROR 1062&#xff1b; 数据库版本 表结构 直接插入操作 - 正常 mysql函数批量插入操作 -ERROR 1062 错误原因 set t…

[23000][1062] Duplicate entry ‘6‘ for key ‘PRIMARY‘

在 DataGrip 里插入数据的时候&#xff0c;我试图修改已经设置成了主键和自增的字段 ID&#xff0c;所以导致了该问题&#xff1a; [23000][1062] Duplicate entry 6 for key PRIMARY 翻译过来的意思&#xff1a;密钥“PRIMARY”的重复条目“6” 原因&#xff1a; 因为 ID 字…