您当前的位置: 首页 >  sql

Dream丶Killer

暂无认证

  • 0浏览

    0关注

    188博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

Dream丶Killer 发布时间:2020-11-10 22:36:26 ,浏览量:0

(异步爬虫)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())
关注
打赏
1655344294
查看更多评论
立即登录/注册

微信扫码登录

0.0439s