Python构建本身的代理IP池

代码

GITHUBhtml

目的

爬虫过程当中,遭遇站点反爬虫策略,须要按期切换IP。因此我构建一个有效的IP池,用于以后的爬虫工做mysql

作法

爬取西刺免费代理IP网,筛选有效的代理IP入库jquery

依赖

  • requests: HTTP请求git

  • pyquery: Python 版的jquery ,解析HTML元素github

  • PyMySQL:mysql ,本实例存储在mysql中。对于数据的操做,数据库仍是更加方便。sql

实现

爬取网页,获取数据

def getProxy(protocal, link, page=1):
    try:
        url = f'https://www.xicidaili.com/{link}/{page}'
        res = requests.get(url, headers={'User-Agent': UA['PC']})
        if (res and res.status_code == 200):
            html = pq(res.text)('#ip_list tr')

            for i in range(html.length):
                host = pq(tds[1]).text()
                port = pq(tds[2]).text()
                
复制代码

如上所示的代码(截取了部分),咱们解析西刺免费代理IP网,获取目标IP 和 端口数据库

检测IP,端口的有效性

西刺免费代理IP网提供的不少IP不具有有效性,因此须要作出过滤才可入库bash

def checkProxy(proxylink):
    try:
        ret = requests.get(
            'https://www.baidu.com',
            proxies={'https': proxylink},
            timeout=5,
        )
        if (ret and ret.status_code == 200):
            print(proxylink)
            return True
    except Exception as e:
         pass
复制代码

咱们使用上面的方法,代理请求百度地址,检测代理的有效性多线程

将有效的IP入库,已在数据库中可是无效的IP,移除

# 链接数据库
def connect():
    try:
        db = pymysql.connect(
            MYSQL['host'],
            MYSQL['username'],
            MYSQL['password'],
            MYSQL['dbname'],
        )
        cursor = db.cursor()
        return {'db': db, 'cursor': cursor}
    except Exception as e:
        print('connect error:', e)

*****
mysql = connect()
# 检查DB 是否已存在某代理地址
mysql['cursor'].execute(
    f'select count(*) from proxy where host = "{host}" and port = "{port}"',
)
# 若是代理有效,且不存在DB中,代理入库
mysql['cursor'].execute(
    f'insert into proxy(host,port,protocal) values("{host}","{port}","{protocal}")'
)
mysql['db'].commit()
# 若是代理无效,可是又存在于DB中,删除代理
mysql['cursor'].execute(
    f'delete from proxy where host = "{host}" and port = "{port}"'
)
mysql['db'].commit()
# 关闭链接
mysql['db'].close()
复制代码

由于须要对每一个代理检测有效性,全部的检测IP有效性、IP入库都基于多线程实现。每一个线程独享一个MYSQL链接。ui

上面阐述的比较碎片,具体的实现能够看源码,代码包含SQL结构。

展现效果

image.png
相关文章
相关标签/搜索