代理IP池的实现

本文获取西刺网免费代理IP,与mysql数据交互。实现代理IP池

from selenium import webdriver
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
import time
import requests
import hashlib
import pymysql
import random


class ProxyIpPool:
    def __init__(self, crawl=True):
        # self.ua = UserAgent()
        host = 'localhost'
        port = 3306
        dbname = 'python_spider'
        user = 'root'
        pwd = '123456'
        self.driver = None
        try:
            self.conn = pymysql.connect(host=host, port=port, user=user, password=pwd, db=dbname, charset='utf8')
            self.cur = self.conn.cursor()
            self.id_list = []
            self.get_from_db()
        except Exception as e:
            print('init:', e)
            # self.close()
        if crawl:
            # 使用谷歌浏览器
            self.driver = webdriver.Chrome()

    def get_from_db(self):
        '''
        从数据库中读取已有的代理ip
        :return:
        '''
        strsql = "select * from proxyippool"
        self.cur.execute(strsql)
        results = self.cur.fetchall()
        for item in results:
            id = item[1]
            ip = item[2]
            port = item[3]
            protocal = item[4].lower()
            proxy = protocal + "://" + ip + ":" + port
            self.id_list.append(id)
            #print(len(self.id_list))

    def down_ips(self, url):
        '''
        下载代理IP
        :param url:
        :return:
        '''
        # 访问地址
        self.driver.get(url)
        # 得到html文件
        html = self.driver.page_source
        # print(html)
        # 建立bs对象
        bs = BeautifulSoup(html, 'lxml')
        ls = bs.select('#ip_list > tbody > tr')
        print(len(ls))
        ls.pop(0)

        for item in ls:
            ip = item.select('td')[1].get_text()
            port = item.select('td')[2].get_text()
            protocal = item.select('td')[5].get_text()
            protocal = protocal.lower()
            proxy = protocal + "://" + ip + ":" + port
            print(proxy)
            if self.check_ip(proxy, protocal):
                print('valid ip.')
                self.save(ip, port, protocal)
            time.sleep(random.random())

    def check_ip(self, ip, protocal):
        '''
        检验ip是否有效
        :param ip:
        :return:
        '''
        # headers = {'User-Agent': self.ua.random}  # 定制请求头
        headers = {'User-Agent': 'Mozilla/5.0 (compatible; WOW64; MSIE 10.0; Windows NT 6.2)'}
        proxies = {}
        proxies = {"http": ip}  # 代理ip
        if protocal == 'https':
            proxies = {"https": ip}  # 代理ip
        print('proxies:', proxies)
        try:
            print('check:', ip)
            url = "http://ip.27399.com/"
            url = "http://www.ip138.com/"
            code = requests.get(url=url, proxies=proxies, headers=headers, timeout=10).status_code
            if code == 200:
                return True
            else:
                return False
        except:
            return False

    def check_all(self):
        '''
        从数据库中读取已有的代理ip,并检验其有效性
        :return:
        '''
        strsql = "select * from proxyippool"
        self.cur.execute(strsql)
        results = self.cur.fetchall()
        for item in results:
            id = item[1]
            ip = item[2]
            port = item[3]
            protocal = item[4].lower()
            proxy = protocal + "://" + ip + ":" + port
            self.id_list.append(id)
            if self.check_ip(proxy,protocal):
                if id not in self.id_list:
                    self.id_list.append(id)
            else:
                self.delRecord(id)
            print(len(self.id_list))

    def save(self, ip, port, protocal):
        '''
        代理ip存储到数据库
        :param ip:
        :param port:
        :return:
        '''
        print('begin save...')
        proxy = ip + ":" + port
        h = hashlib.md5()
        h.update(proxy.encode())
        id = h.hexdigest()
        if id not in self.id_list:
            try:
                strsql = 'insert into proxyippool VALUES(0,%s,%s,%s,%s)'
                params = (id, ip, port, protocal)
                result = self.cur.execute(strsql, params)
                self.conn.commit()
                self.id_list.append(id)
                print('save:', proxy)
            except Exception as e:
                print('save:', e)
                self.close()

    def get_proxy(self):
        '''
        随机提取可用的代理ip
        :return:
        '''
        if len(self.id_list) <= 0:
            return None
        id = random.choice(self.id_list)
        print('id:', id)
        strsql = 'select * from proxyippool where idname="' + id + '"'
        self.cur.execute(strsql)
        result = self.cur.fetchone()
        if result != None:
            ip = result[2]
            port = result[3]
            protocal = result[4]
            print('protocal:', protocal)
            proxy = protocal + "://" + ip + ":" + port
            if self.check_ip(proxy, protocal):
                return proxy
            else:
                self.delRecord(id)
                self.get_proxy()
        else:
            self.get_proxy()

    def delRecord(self, id):
        '''
        删除指定的记录
        :param self:
        :param id:
        :return:
        '''
        strsql = 'delete from proxyippool where idname="' + id + '"'
        self.cur.execute(strsql)
        self.conn.commit()
        self.id_list.remove(id)
        print('del proxy:', id)

    def close(self):
        try:
            if self.driver:
                self.driver.close()
            self.cur.close()
            self.conn.close()
        except Exception as e:
            print(e)


if __name__ == '__main__':
	#爬取可用IP
    # pool = ProxyIpPool()
    # for i in range(1,6):
    #     print('down page:',i)
    #     url = "http://www.xicidaili.com/nn/"+str(i)
    #     pool.down_ips(url)
    # pool.close()
    
	# 获取可用IP
    pool = ProxyIpPool(crawl=False)
    print(pool.get_proxy())
    # print(len(pool.id_list))
    # print(pool.id_list)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Scrapy是一个强大的Python爬虫框架,可以用于抓取和提取网页数据。如果你想在Scrapy中使用代理IP,可以按照以下步骤进行: 1. 首先,你需要准备一个代理IP。这可以是一个存储代理IP的数据库或者一个包含代理IP列表的文件。 2. 在Scrapy的项目中,你可以创建一个中间件来处理代理IP。中间件可以在请求发送之前或之后修改请求。你可以创建一个自定义的中间件类,在其中实现代理IP的设置。 例如,你可以创建一个名为ProxyMiddleware的中间件类,并在其中实现process_request方法,从代理IP中随机选择一个代理IP,并将其设置为请求的代理。 ```python class ProxyMiddleware(object): def process_request(self, request, spider): # 从代理IP中随机选择一个代理IP proxy = get_proxy_ip() request.meta['proxy'] = proxy ``` 3. 将中间件添加到Scrapy的配置中。在项目的settings.py文件中,找到DOWNLOADER_MIDDLEWARES配置项,并将你的中间件类添加到其中。 ```python DOWNLOADER_MIDDLEWARES = { 'your_project_name.middlewares.ProxyMiddleware': 543, # 其他中间件... } ``` 4. 现在,当Scrapy发送请求时,中间件会在请求前设置代理IP。这样,你就可以使用代理IP来爬取网页数据了。 请注意,使用代理IP需要注意合法性和稳定性。你需要确保代理IP有效,并及时更新代理IP,以免影响爬虫的正常运行。另外,使用代理IP时也需要遵守网站的相关规定,避免对目标网站造成不必要的干扰。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值