3

爬虫必备反爬技能:使用动态ip

 2 years ago
source link: https://blog.csdn.net/weixin_46211269/article/details/122083331
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

一、为什么要使用动态代理ip?

使用它的好处在哪里呢?

  1. 保护你的网络免受外部攻击
  2. 屏蔽你的IP地址
  3. 限制不必要的内容
  4. 更好的帮助你抓取网络数据
  5. 绕过目标网站限制。网站一般会限制单个ip请求数量,使用动态ip可以自定义时间更换ip地址,提高爬虫效率。
  6. 隐藏真实ip地址。出于各种安全原因,有些人选择使用代理来隐藏其真实IP地址。

以上几点,足以知道使用代理动态ip的好处,难不成还用自己电脑的ip呢?ip是能定位到你的好吧,所以咱一般不用自己的本地ip爬(简单的本地爬,某些数据还是要使用代理ip哈)

二、如何申请动态代理ip?

我随便使用的一个代理ip网站。反正你们随便找个代理网站都行。看谁福利多就用谁的咯,这个我只是测试。
在这里插入图片描述
生成代理api
在这里插入图片描述
点击生成链接:
在这里插入图片描述
认证一下:
在这里插入图片描述
再返回,点击生成链接,复制链接(保存在文档):
在这里插入图片描述

三、如何使用动态ip?

我们就是用最简单的requests模块:

import requests

然后我们再加上随机请求头模块(反爬用):

from fake_useragent import UserAgent

导入请求的url和随机请求头:

url='https://blog.csdn.net/weixin_46211269?spm=1011.2124.3001.5343'

headers={'User-Agent':UserAgent().random}

使用api获取到ip:(记得换成你自己的api)

# proxies = {'协议': '协议://IP:端口号'}
api_url='http://tiqu.ipidea.io:81/abroad?num=1&type=1&lb=1&sb=0&flow=1&regions=&port=1'

res = requests.post(api_url,headers=headers, verify=True)
proxie = "https://%s"%(res.text)
proxies = {'http': proxie}
print(proxies)

请求网址(以我自己的博客链接为例子):

html=requests.get(url=url,headers=headers,proxies=proxies).text
print(html)

完整源码:

import requests
from fake_useragent import UserAgent

url='https://blog.csdn.net/weixin_46211269?spm=1011.2124.3001.5343'

headers={'User-Agent':UserAgent().random}

# proxies = {'协议': '协议://IP:端口号'}
api_url='http://tiqu.ipidea.io:81/abroad?num=1&type=1&lb=1&sb=0&flow=1&regions=&port=1'

res = requests.post(api_url,headers=headers, verify=True)
proxie = "https://%s"%(res.text)
proxies = {'http': proxie}
print(proxies)

html=requests.get(url=url,headers=headers,proxies=proxies).text
print(html)

运行如下:
在这里插入图片描述
更多案例和具体实战我已经在前面的文章讲过了,这里主要是教一下大家如何使用代理ip,只是在原来的基础上加了一个代理ip。代理ip对于爬虫手来说,用处很大,一定要学会哇!

四、我猜你还有的疑问

你看到本篇爬虫教程的时候,你给我说你连python基础都不会?那我推荐你看我的基础教程专栏:python全栈基础教程
专栏好不好,粉丝们说了算:
在这里插入图片描述
基础学完后再来本专栏的爬虫教程,一直都在更新,更新期间免费白嫖!三连好评一下,持续输出优质能容,最近更新慢,寒假再卷你们。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK