(异步爬虫)aiomysql剔除代理池中失效的IP

(异步爬虫)aiomysql剔除代理池中失效的IP


最近写的几个爬虫,都因为IP被封的原因,爬取的数据很少,尽管已经限制访问的时间,但时间长了,一直使用同一个IP必然有风险。所以趁着现在课少,写了个简单的代理池(仅供自用),目前还在一步步完善。下面就异步mysql和异步IP测试来简单记录一下。

在这里插入图片描述
之前没怎么用协程,这次使用踩了不少坑。。话不多说直接开整。
首先要做的肯定是获取当前数据库中已有的ip。由于只取一次,就直接pymysql来进行操作了。

def query_db():
    conn = pymysql.Connect(host='127.0.0.1', port=3306, user='root', password='xxxxxx', db='proxy_pool', charset='utf8', autocommit=True)
    cur = conn.cursor()
    cur.execute("select ip from proxies")
    # result返回结果是元组,ip以元组的形式保存在元组内(('111.2.3.4:9999'),)
    result = cur.fetchall()
    return result

获取了数据,当然是ip测试,有用的留下,没用的删除。。

async def ip_test(proxy):
    async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:
        try:
            async with session.get('http://httpbin.org/ip', proxy="http://{}".format(proxy), timeout=6) as response:
                print('ip可用', proxy)
        except Exception as e:
            await delete_ip(proxy)
            print(proxy, '已从库中删除')

async def delete_ip(proxy):
    conn = await aiomysql.connect(host='127.0.0.1', port=3306, user='root', password='xxxxxx', db='proxy_pool', charset='utf8',autocommit=True)
    cur = await conn.cursor()
    await cur.execute("delete from proxies where ip='{}'".format(proxy))
    await cur.close()
    conn.close()

connector=aiohttp.TCPConnector(ssl=False) 这个参数最好加上,不然ssl证书可能报错。
最后上主函数代码

async def main():
	# 获取数据库中的ip元组
    ip_tup = query_db()
    async with aiohttp.ClientSession() as session:
    	# 将协程对象添加到任务列表
        tasks = [ip_test(''.join(proxy)) for proxy in ip_tup]
        await asyncio.wait(tasks)

if __name__=='__main__':
    asyncio.run(main())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dream丶Killer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值