一、简介

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

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

- 代理的分类:

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

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

- 免费代理ip提供网站

  http://www.goubanjia.com/

  西刺代理

  快代理

匿名度

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

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

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

类型:

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

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

示例

  1. import requests
  2.  
  3. headers = {
  4. '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'
  5. }
  6. url = 'https://www.baidu.com/s?wd=ip'
  7.  
  8. # 不同的代理IP,代理ip的类型必须和请求url的协议头保持一致
  9. proxy_list = [
  10. {"http": "112.115.57.20:3128"},
  11. {'http': '121.41.171.223:3128'}
  12. ]
  13.  
  14. # 随机获取代理IP
  15. proxy = random.choice(proxy_list)
  16.  
  17. page_text = requests.get(url=url,headers=headers,proxies=proxy).text
  18.  
  19. with open('ip.html','w',encoding='utf-8') as fp:
  20. fp.write(page_text)
  21.  
  22. print('over!')

二、IP池

1、免费IP池

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

  1. import requests
  2. from lxml import etree
  3. import time
  4. import random
  5. from fake_useragent import UserAgent
  6.  
  7. class GetProxyIP(object):
  8. def __init__(self):
  9. self.url = 'https://www.xicidaili.com/nn/'
  10. self.proxies = {
  11. 'http': 'http://163.204.247.219:9999',
  12. 'https': 'http://163.204.247.219:9999'}
  13.  
  14. # 随机生成User-Agent
  15. def get_random_ua(self):
  16. ua = UserAgent() # 创建User-Agent对象
  17. useragent = ua.random
  18. return useragent
  19.  
  20. # 从西刺代理网站上获取随机的代理IP
  21. def get_ip_file(self, url):
  22. headers = {'User-Agent': self.get_random_ua()}
  23. html = requests.get(url=url, proxies=self.proxies, headers=headers, timeout=5).content.decode('utf-8', 'ignore')
  24. parse_html = etree.HTML(html)
  25. tr_list = parse_html.xpath('//tr') # 基准xpath,匹配每个代理IP的节点对象列表
  26.  
  27. for tr in tr_list[1:]:
  28. ip = tr.xpath('./td[2]/text()')[0]
  29. port = tr.xpath('./td[3]/text()')[0]
  30. self.test_proxy_ip(ip, port) # 测试ip:port是否可用
  31.  
  32. # 测试抓取的代理IP是否可用
  33. def test_proxy_ip(self, ip, port):
  34. proxies = {
  35. 'http': 'http://{}:{}'.format(ip, port),
  36. 'https': 'https://{}:{}'.format(ip, port), }
  37. test_url = 'http://www.baidu.com/'
  38. try:
  39. res = requests.get(url=test_url, proxies=proxies, timeout=8)
  40. if res.status_code == 200:
  41. print(ip, ":", port, 'Success')
  42. with open('proxies.txt', 'a') as f:
  43. f.write(ip + ':' + port + '\n')
  44. except Exception as e:
  45. print(ip, port, 'Failed')
  46.  
  47. def main(self):
  48. for i in range(1, 1001):
  49. url = self.url.format(i)
  50. self.get_ip_file(url)
  51. time.sleep(random.randint(5, 10))
  52.  
  53. if __name__ == '__main__':
  54. spider = GetProxyIP()
  55. spider.main()

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

  1. import random
  2. import requests
  3.  
  4. class BaiduSpider(object):
  5. def __init__(self):
  6. self.url = 'http://www.baidu.com/'
  7. self.headers = {'User-Agent': 'Mozilla/5.0'}
  8. self.flag = 1
  9.  
  10. def get_proxies(self):
  11. with open('proxies.txt', 'r') as f:
  12. result = f.readlines() # 读取所有行并返回列表
  13. proxy_ip = random.choice(result)[:-1] # 获取了所有代理IP
  14. L = proxy_ip.split(':')
  15. proxy_ip = {
  16. 'http': 'http://{}:{}'.format(L[0], L[1]),
  17. 'https': 'https://{}:{}'.format(L[0], L[1])
  18. }
  19. return proxy_ip
  20.  
  21. def get_html(self):
  22. proxies = self.get_proxies()
  23. if self.flag <= 3:
  24. try:
  25. html = requests.get(url=self.url, proxies=proxies, headers=self.headers, timeout=5).text
  26. print(html)
  27. except Exception as e:
  28. print('Retry')
  29. self.flag += 1
  30. self.get_html()
  31. if __name__ == '__main__':
  32. spider = BaiduSpider()
  33. spider.get_html()

2.收费代理API

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

  1. import requests
  2. from fake_useragent import UserAgent
  3.  
  4. ua = UserAgent() # 创建User-Agent对象
  5. useragent = ua.random
  6. headers = {'User-Agent': useragent}
  7.  
  8. def ip_test(ip):
  9. url = 'http://www.baidu.com/'
  10. ip_port = ip.split(':')
  11. proxies = {
  12. 'http': 'http://{}:{}'.format(ip_port[0], ip_port[1]),
  13. 'https': 'https://{}:{}'.format(ip_port[0], ip_port[1]),
  14. }
  15. res = requests.get(url=url, headers=headers, proxies=proxies, timeout=5)
  16. if res.status_code == 200:
  17. return True
  18. else:
  19. return False
  20. # 提取代理IP
  21. def get_ip_list():
  22. # 快代理:https://www.kuaidaili.com/doc/product/dps/
  23. api_url = 'http://dev.kdlapi.com/api/getproxy/?orderid=946562662041898&num=100&protocol=1&method=2&an_an=1&an_ha=1&sep=2'
  24. html = requests.get(api_url).content.decode('utf-8', 'ignore')
  25. ip_port_list = html.split('\n')
  26.  
  27. for ip in ip_port_list:
  28. with open('proxy_ip.txt', 'a') as f:
  29. if ip_test(ip):
  30. f.write(ip + '\n')
  31.  
  32. if __name__ == '__main__':
  33. get_ip_list()

3.私密代理

1、语法结构

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

  1. proxies = {
  2. '协议':'协议://用户名:密码@IP:端口号'
  3. }
  4. proxies = {
  5. 'http':'http://用户名:密码@IP:端口号',
  6. 'https':'https://用户名:密码@IP:端口号'
  7. }
  8. proxies = {
  9. 'http': 'http://309435365:szayclhp@106.75.71.140:16816',
  10. 'https':'https://309435365:szayclhp@106.75.71.140:16816',
  11. }
  1. # 获取开放代理的接口
  2. import requests
  3. from fake_useragent import UserAgent
  4.  
  5. ua = UserAgent() # 创建User-Agent对象
  6. useragent = ua.random
  7. headers = {'User-Agent': useragent}
  8.  
  9. def ip_test(ip):
  10. url = 'https://blog.csdn.net/qq_34218078/article/details/90901602/'
  11. ip_port = ip.split(':')
  12. proxies = {
  13. 'http': 'http://1786088386:b95djiha@{}:{}'.format(ip_port[0], ip_port[1]),
  14. 'https': 'http://1786088386:b95djiha@{}:{}'.format(ip_port[0], ip_port[1]),
  15. }
  16.  
  17. res = requests.get(url=url, headers=headers, proxies=proxies, timeout=5)
  18. if res.status_code == 200:
  19. print("OK")
  20. return True
  21. else:
  22. print(res.status_code)
  23. print("错误")
  24. return False
  25.  
  26. # 提取代理IP
  27. def get_ip_list():
  28. # 快代理:https://www.kuaidaili.com/doc/product/dps/
  29. api_url = 'http://dps.kdlapi.com/api/getdps/?orderid=986603271748760&num=1000&signature=z4a5b2rpt062iejd6h7wvox16si0f7ct&pt=1&sep=2'
  30. html = requests.get(api_url).content.decode('utf-8', 'ignore')
  31. ip_port_list = html.split('\n')
  32.  
  33. for ip in ip_port_list:
  34. with open('proxy_ip.txt', 'a') as f:
  35. if ip_test(ip):
  36. f.write(ip + '\n')
  37.  
  38. if __name__ == '__main__':
  39. get_ip_list()

思路:

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

Python爬虫 | IP池的使用的更多相关文章

  1. Python爬虫代理池

    爬虫代理IP池 在公司做分布式深网爬虫,搭建了一套稳定的代理池服务,为上千个爬虫提供有效的代理,保证各个爬虫拿到的都是对应网站有效的代理IP,从而保证爬虫快速稳定的运行,当然在公司做的东西不能开源出来 ...

  2. Python爬虫-代理池-爬取代理入库并测试代理可用性

    目的:建立自己的代理池.可以添加新的代理网站爬虫,可以测试代理对某一网址的适用性,可以提供获取代理的 API. 整个流程:爬取代理 ----> 将代理存入数据库并设置分数 ----> 从数 ...

  3. 设置python爬虫IP代理(urllib/requests模块)

    urllib模块设置代理 如果我们频繁用一个IP去爬取同一个网站的内容,很可能会被网站封杀IP.其中一种比较常见的方式就是设置代理IP from urllib import request proxy ...

  4. Python爬虫代理IP池

    目录[-] 1.问题 2.代理池设计 3.代码模块 4.安装 5.使用 6.最后 在公司做分布式深网爬虫,搭建了一套稳定的代理池服务,为上千个爬虫提供有效的代理,保证各个爬虫拿到的都是对应网站有效的代 ...

  5. python爬虫18 | 就算你被封了也能继续爬,使用IP代理池伪装你的IP地址,让IP飘一会

    我们上次说了伪装头部 ↓ python爬虫17 | 听说你又被封 ip 了,你要学会伪装好自己,这次说说伪装你的头部 让自己的 python 爬虫假装是浏览器 小帅b主要是想让你知道 在爬取网站的时候 ...

  6. python爬虫构建代理ip池抓取数据库的示例代码

    爬虫的小伙伴,肯定经常遇到ip被封的情况,而现在网络上的代理ip免费的已经很难找了,那么现在就用python的requests库从爬取代理ip,创建一个ip代理池,以备使用. 本代码包括ip的爬取,检 ...

  7. Python爬虫之ip代理池

    可能在学习爬虫的时候,遇到很多的反爬的手段,封ip 就是其中之一. 对于封IP的网站.需要很多的代理IP,去买代理IP,对于初学者觉得没有必要,每个卖代理IP的网站有的提供了免费IP,可是又很少,写了 ...

  8. python开源IP代理池--IPProxys

    今天博客开始继续更新,谢谢大家对我的关注和支持.这几天一直是在写一个ip代理池的开源项目.通过前几篇的博客,我们可以了解到突破反爬虫机制的一个重要举措就是代理ip.拥有庞大稳定的ip代理,在爬虫工作中 ...

  9. Python 爬虫的代理 IP 设置方法汇总

    本文转载自:Python 爬虫的代理 IP 设置方法汇总 https://www.makcyun.top/web_scraping_withpython15.html 需要学习的地方:如何在爬虫中使用 ...

随机推荐

  1. golang笔记之DOS篇

    Dos的常用命令 dos的基本介绍     Dos: Disk Operating System 磁盘操作系统  ,简单说一下Windows下的目录 2. dos的基本操作原理   目录的操作: md ...

  2. OracleVM桥接网卡无法获取本地连接网卡

    问题现象 VM虚拟机采用桥接网卡时,界面名称为"未指定",无法获取本地连接对应网卡信息: 处理方式: 进入本地连接,选择本地连接右键进入属性设置窗口; 选择安装,单击服务选项后点击 ...

  3. robotframework_接口自动化

    我们在使用rebotframework的时候,不只是能做UI自动化,接口自动化也是可以的. 那么这里就整理一下rebotframework_接口自动化的应用: 一.编写接口测试 由上图可知,该接口如下 ...

  4. Codeforces Round #499 (Div. 1) F. Tree

    Codeforces Round #499 (Div. 1) F. Tree 题目链接 \(\rm CodeForces\):https://codeforces.com/contest/1010/p ...

  5. 如何监视 WPF 中的所有窗口,在所有窗口中订阅事件或者附加 UI

    原文:如何监视 WPF 中的所有窗口,在所有窗口中订阅事件或者附加 UI 由于 WPF 路由事件(主要是隧道和冒泡)的存在,我们很容易能够通过只监听窗口中的某些事件使得整个窗口中所有控件发生的事件都被 ...

  6. 使用Powershell实现自动化安装/卸载程序

    最近需要制作软件安装包,需要附带VC运行时和.Net Framework的安装,但又不想让用户自己点下一步,所以就有了以下操作. 微软提供了一个程序叫msiexec.exe,位于C:\Windows\ ...

  7. 无法定位 Local Database Runtime 安装。请验证 SQL Server Express 是否正确安装以及本地数据库运行时功能是否已启用。

    错误描述: 在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误.未找到或无法访问服务器.请验证实例名称是否正确并且 SQL Server 已配置为允许远程连接. (provide ...

  8. rabbitmq监控之消息确认ack

    rabbitmq springboot ack 监控 一.测试环境 二.启动测试 一直以来,学习rabbitmq都是跟着各种各样的教程.博客.视频和文档,撸起袖子就是干!!!最后,也成功了. 当然,成 ...

  9. Django:基于调试组插件go-debug-toolbar

    1.django-debug-toolbar 介绍 django-debug-toolbar 是一组可配置的面板,可显示有关当前请求/响应的各种调试信息,并在单击时显示有关面板内容的更多详细信息.返回 ...

  10. nodejs SSL Error: CERT_UNTRUSTED while using npm command 错误

    SSH 使用错误,其实我们关掉HTTPS就好了 npm config set strict-ssl false 或者 npm config set registry="http://regi ...