Python 爬虫IP代理池的实现

简介:

很多时候,如果要多线程的爬取网页,或者是单纯的反爬,我们需要通过代理IP来进行访问。下面看看一个基本的实现方法。

代理IP的提取,网上有很多网站都提供这个服务。基本上可靠性和银子是成正比的。国内提供的免费IP基本上都是没法用的,如果要可靠的代理只能付费;国外稍微好些,有些免费IP还是比较靠谱的。

网上随便搜索了一下,找了个网页,本来还想手动爬一些对应的IP,结果发现可以直接下载现成的txt文件
http://www.thebigproxylist.com/

下载之后,试试看用不同的代理去爬百度首页

#!/usr/bin/env python
#! -*- coding:utf-8 -*-
# Author: Yuan Li

import re,urllib.request

fp=open("c:\\temp\\thebigproxylist-17-12-20.txt",'r')
lines=fp.readlines()

for ip in lines:
    try:
            print("当前代理IP "+ip)
            proxy=urllib.request.ProxyHandler({"http":ip})
            opener=urllib.request.build_opener(proxy,urllib.request.HTTPHandler)
            urllib.request.install_opener(opener)
            url="http://www.baidu.com"
            data=urllib.request.urlopen(url).read().decode('utf-8','ignore')
            print("通过")

            print("-----------------------------")
    except Exception as err:
        print(err)
        print("-----------------------------")

fp.close()

结果如下:


C:\Python36\python.exe C:/Users/yuan.li/Documents/GitHub/Python/Misc/爬虫/proxy.py
当前代理IP 137.74.168.174:80

通过
-----------------------------
当前代理IP 103.28.161.68:8080

通过
-----------------------------
当前代理IP 91.151.106.127:53281

HTTP Error 503: Service Unavailable
-----------------------------
当前代理IP 177.136.252.7:3128

<urlopen error [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond>
-----------------------------
当前代理IP 47.89.22.200:80

通过
-----------------------------
当前代理IP 118.69.61.57:8888

HTTP Error 503: Service Unavailable
-----------------------------
当前代理IP 192.241.190.167:8080

通过
-----------------------------
当前代理IP 185.124.112.130:80

通过
-----------------------------
当前代理IP 83.65.246.181:3128

通过
-----------------------------
当前代理IP 79.137.42.124:3128

通过
-----------------------------
当前代理IP 95.0.217.32:8080

<urlopen error [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond>
-----------------------------
当前代理IP 104.131.94.221:8080

通过

不过上面这种方式只适合比较稳定的IP源,如果IP不稳定的话,可能很快对应的文本就失效了,最好可以动态地去获取最新的IP地址。很多网站都提供API可以实时地去查询
还是用刚才的网站,这次我们用API去调用,这里需要浏览器伪装一下才能爬取

#!/usr/bin/env python
#! -*- coding:utf-8 -*-
# Author: Yuan Li

import re,urllib.request

headers=("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.22 Safari/537.36 SE 2.X MetaSr 1.0")
opener=urllib.request.build_opener()
opener.addheaders=[headers]
#安装为全局
urllib.request.install_opener(opener)
data=urllib.request.urlopen("http://www.thebigproxylist.com/members/proxy-api.php?output=all&user=list&pass=8a544b2637e7a45d1536e34680e11adf").read().decode('utf8')
ippool=data.split('\n')

for ip in ippool:
    ip=ip.split(',')[0]
    try:
            print("当前代理IP "+ip)
            proxy=urllib.request.ProxyHandler({"http":ip})
            opener=urllib.request.build_opener(proxy,urllib.request.HTTPHandler)
            urllib.request.install_opener(opener)
            url="http://www.baidu.com"
            data=urllib.request.urlopen(url).read().decode('utf-8','ignore')
            print("通过")

            print("-----------------------------")
    except Exception as err:
        print(err)
        print("-----------------------------")

fp.close()

结果如下:


C:\Python36\python.exe C:/Users/yuan.li/Documents/GitHub/Python/Misc/爬虫/proxy.py
当前代理IP 213.233.57.134:80
HTTP Error 403: Forbidden
-----------------------------
当前代理IP 144.76.81.79:3128
通过
-----------------------------
当前代理IP 45.55.132.29:53281
HTTP Error 503: Service Unavailable
-----------------------------
当前代理IP 180.254.133.124:8080
通过
-----------------------------
当前代理IP 5.196.215.231:3128
HTTP Error 503: Service Unavailable
-----------------------------
当前代理IP 177.99.175.195:53281
HTTP Error 503: Service Unavailable

因为直接for循环来按顺序读取文本实在是太慢了,我试着改成多线程来读取,这样速度就快多了

#!/usr/bin/env python
#! -*- coding:utf-8 -*-
# Author: Yuan Li

import threading
import queue
import re,urllib.request

#Number of threads
n_thread = 10
#Create queue
queue = queue.Queue()

class ThreadClass(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
                super(ThreadClass, self).__init__()
    #Assign thread working with queue
        self.queue = queue

    def run(self):
        while True:
        #Get from queue job
            host = self.queue.get()
            print (self.getName() + ":" + host)
            try:
                # print("当前代理IP " + host)
                proxy = urllib.request.ProxyHandler({"http": host})
                opener = urllib.request.build_opener(proxy, urllib.request.HTTPHandler)
                urllib.request.install_opener(opener)
                url = "http://www.baidu.com"
                data = urllib.request.urlopen(url).read().decode('utf-8', 'ignore')
                print("通过")

                print("-----------------------------")
            except Exception as err:
                print(err)
                print("-----------------------------")

            #signals to queue job is done
            self.queue.task_done()

#Create number process
for i in range(n_thread):
    t = ThreadClass(queue)
    t.setDaemon(True)
    #Start thread
    t.start()

#Read file line by line
hostfile = open("c:\\temp\\thebigproxylist-17-12-20.txt","r")
for line in hostfile:
    #Put line to queue
    queue.put(line)
#wait on the queue until everything has been processed
queue.join()





本文转自 beanxyz 51CTO博客,原文链接:http://blog.51cto.com/beanxyz/2052791,如需转载请自行联系原作者

目录
相关文章
|
4月前
|
数据采集 Web App开发 数据安全/隐私保护
实战:Python爬虫如何模拟登录与维持会话状态
实战:Python爬虫如何模拟登录与维持会话状态
|
5月前
|
数据采集 Web App开发 自然语言处理
新闻热点一目了然:Python爬虫数据可视化
新闻热点一目了然:Python爬虫数据可视化
|
5月前
|
数据采集 运维 监控
构建企业级Selenium爬虫:基于隧道代理的IP管理架构
构建企业级Selenium爬虫:基于隧道代理的IP管理架构
|
6月前
|
数据采集 数据挖掘 测试技术
Go与Python爬虫实战对比:从开发效率到性能瓶颈的深度解析
本文对比了Python与Go在爬虫开发中的特点。Python凭借Scrapy等框架在开发效率和易用性上占优,适合快速开发与中小型项目;而Go凭借高并发和高性能优势,适用于大规模、长期运行的爬虫服务。文章通过代码示例和性能测试,分析了两者在并发能力、错误处理、部署维护等方面的差异,并探讨了未来融合发展的趋势。
542 0
|
4月前
|
数据采集 监控 数据库
Python异步编程实战:爬虫案例
🌟 蒋星熠Jaxonic,代码为舟的星际旅人。从回调地狱到async/await协程天堂,亲历Python异步编程演进。分享高性能爬虫、数据库异步操作、限流监控等实战经验,助你驾驭并发,在二进制星河中谱写极客诗篇。
Python异步编程实战:爬虫案例
|
5月前
|
数据采集 存储 XML
Python爬虫技术:从基础到实战的完整教程
最后强调: 父母法律法规限制下进行网络抓取活动; 不得侵犯他人版权隐私利益; 同时也要注意个人安全防止泄露敏感信息.
863 19
|
4月前
|
数据采集 存储 JSON
Python爬虫常见陷阱:Ajax动态生成内容的URL去重与数据拼接
Python爬虫常见陷阱:Ajax动态生成内容的URL去重与数据拼接
|
4月前
|
数据采集 存储 JavaScript
解析Python爬虫中的Cookies和Session管理
Cookies与Session是Python爬虫中实现状态保持的核心。Cookies由服务器发送、客户端存储,用于标识用户;Session则通过唯一ID在服务端记录会话信息。二者协同实现登录模拟与数据持久化。
|
5月前
|
数据采集 存储 Web App开发
处理Cookie和Session:让Python爬虫保持连贯的"身份"
处理Cookie和Session:让Python爬虫保持连贯的"身份"
|
6月前
|
数据采集 存储 JSON
地区电影市场分析:用Python爬虫抓取猫眼/灯塔专业版各地区票房
地区电影市场分析:用Python爬虫抓取猫眼/灯塔专业版各地区票房

推荐镜像

更多