(异步爬虫)requests和aiohttp中代理IP的使用

(异步爬虫)requests和aiohttp中代理IP的使用


爬虫要想爬的好,IP代理少不了。。现在网站基本都有些反爬措施,访问速度稍微快点,就会发现IP被封,不然就是提交验证。下面就两种常用的模块来讲一下代理IP的使用方式。话不多说,直接开始。


requests中代理IP的使用:
requests中使用代理IP只需要添加一个proxies参数即可。proxies的参数值是一个字典,key是代理协议(http/https),value就是ip和端口号,具体格式如下。

try:
    response = requests.get('https://httpbin.org/ip', headers=headers, 
    	proxies={'https':'https://221.122.91.74:9401'}, timeout=6)
    print('success')
    # 检测代理IP是否使用成功
    # 第一种方式,返回发送请求的IP地址,使用时要在 get() 添加 stream = True
    # print(response.raw._connection.sock.getpeername()[0])
    # 第二种方式,直接返回测试网站的响应数据的内容
    print(response.text)
except Exception as e:
    print('error',e)

在这里插入图片描述
注意: peoxieskey值(http/https)要和url一致,不然会直接使用本机IP直接访问。

aiohttp中代理IP的使用:
由于requests模块不支持异步,迫不得已使用aiohttp,掉了不少坑。
它的使用方式和requests相似,也是在get()方法中添加一个参数,但此时的参数名为proxy,参数值是字符串,且字符串中的代理协议,只支持http,写成https会报错。
这里记录一下我的纠错历程。。
首先根据网上的使用方式,我先试了一下下面的代码。

async def func():
    async with aiohttp.ClientSession() as session:
        try:
            async with session.get("https://httpbin.org/ip", headers=headers, 
            			proxy='http://183.220.145.3:80', timeout=6) as response:
                page_text = await response.text()
                print('success')
                print(page_text)
        except Exception as e:
            print(e)
            print('error')

if __name__=='__main__':
    asyncio.run(func())

在这里插入图片描述
修改后,再来

async def func():
    con = aiohttp.TCPConnector(verify_ssl=False)
    async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
        try:
            async with session.get("https://httpbin.org/ip", headers=headers, 
            proxy='http://183.220.145.3:80', timeout=6) as response:
                # print(response.raw._connection.sock.getpeername()[0])
                page_text = await response.text()
                print(page_text)
                print('success')
        except Exception as e:
            print(e)
            print('error')

在这里插入图片描述
在这里插入图片描述
非但没有解决反倒多了一个警告,好在改一下就好。额~懒得粘了,直接来最终版本吧。。

# 修改事件循环的策略,不能放在协程函数内部,这条语句要先执行
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
async def func():
	# 添加trust_env=True
    async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False), trust_env=True) as session:
        try:
            async with session.get("https://httpbin.org/ip", headers=headers,
             proxy='http://183.220.145.3:80', timeout=10) as response:
                page_text = await response.text()
                print(page_text)
                print('success')
        except Exception as e:
            print(e)
            print('error')

在这里插入图片描述
虽然纠错过程有点长,但好在知道怎么用了。

对于刚入门 Python 或是想要入门 Python 的小伙伴,可以通过下方小卡片联系作者,一起交流学习,都是从新手走过来的,有时候一个简单的问题卡很久,但可能别人的一点拨就会恍然大悟,由衷的希望大家能够共同进步。另外还有本人整理的近千套模板,百本优质电子书资源,等你领取!

👇🏻 关注小卡片,一起学习Python,领取资料👇🏻
  • 13
    点赞
  • 55
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Dream丶Killer

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

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

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

打赏作者

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

抵扣说明:

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

余额充值