美文网首页
爬虫12-使用IP代理防止被反爬

爬虫12-使用IP代理防止被反爬

作者: Yan雪杉 | 来源:发表于2019-03-15 17:22 被阅读0次

大家好,昨天我们讨论了一下爬虫与反爬虫之间的对抗,不可谓不激烈,今天我们主要来讨论应对反爬虫中非常重要的一种手段,那就是IP代理。

正常来说,我们访问一个URL是这样的:

image.png

客户端向URL所在的服务器发起请求,是会携带本机IP地址的,这样服务器就能获取到我们的IP地址,当这个IP地址在一个时间段内发起请求过于频繁,可能就会限制其一段时间内无法访问。

在编写爬虫程序的过程中,为了防止这种情况发生,就需要用到IP代理,IP代理的原理是这样的:

image.png

第一步:我们会向代理服务器发起请求,告诉代理服务器我们要访问https://www.zhihu.com
第二步:代理服务器会代替我们向https://www.zhihu.com发起请求
第三步:服务器接收到代理服务器发来的请求后,就会将数据返回给代理服务器
第四步:代理服务器接收到服务器返回的数据后,就会将数据发送给客户端

这样,通过代理服务器向URL所在的服务器发起请求,就能完美地隐藏我们自身的IP,从而使得我们的IP不会被限制访问。

但是这样做,当然会有代价,我们通过IP代理来获取我们想要的数据,需要通过代理服务器转发一下,这样自然就会导致爬取的速度变慢,只有使用本机IP发起请求才是最快的。

接下来,我们还是老规矩,通过代码来演示下如何通过IP代理来发起请求:

import requests

# 免费代理可以从https://www.xicidaili.com/中获取到,但是免费的ip代理存活率很低
proxy = {
    'http': '183.148.158.64:9999'
}

res = requests.get('https://www.baidu.com', proxies=proxy)
print(res.text)
# 如果能正确返回结果,那么就说明当前ip代理是存活的,是可以用的,否则当前ip代理是失效的

仅仅有一个代理ip是不够的,我们应该维护一个属于自己的ip代理池,当某一个ip代理失效的时候,就将它剔除出去,那么如何维护一个可用的ip代理池呢?

# 第一步:通过https://www.xicidaili.com/wt/获取到ip_list

import requests
from bs4 import BeautifulSoup
import random

def get_ip_list(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'
    }
    res = requests.get(url, headers=headers)
    res = BeautifulSoup(res.text, 'html.parser')
    results = res.select('#ip_list tr')
    for result in results[1:]:
        ip = result.select('td')[1].text
        port = result.select('td')[2].text
        judge(ip, port)
        # 获取到了ip之后,并不能直接保存,首先应该判断是否可用
# 第二步:判断获取到的ip是否有效

ip_list = []

def judge(ip, port):
    proxy = {'http': ip+':'+port}
    try:
        res = requests.get('https://www.baidu.com', proxies=proxy)
    except Exception:
        print('该ip:' + ip + '无效')
        return False
    else:
        if 200 <= res.status_code < 300:
        # 返回的状态码在200到300之间表示请求成功
            ip_list.append((ip, port))
            return True
        else:
            print('该ip:' + ip + '无效')
            return False
# 第三步:从ip_list中随机获取一个ip

def get_random_ip():
    ip, port = random.choice(ip_list)
    result = judge(ip, port)
    if result:
        return ip + ':' + port
    else:
        ip_list.remove((ip, port))
# 第四步:调用上述函数

if __name__ == '__main__':
    get_ip_list('https://www.xicidaili.com/wt/')
    print(ip_list)
    print(len(ip_list))

完整代码如下:

import requests
from bs4 import BeautifulSoup
import random

ip_list = []

def get_ip_list(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'
    }
    res = requests.get(url, headers=headers)
    res = BeautifulSoup(res.text, 'html.parser')
    results = res.select('#ip_list tr')
    for result in results[1:]:
        ip = result.select('td')[1].text
        port = result.select('td')[2].text
        judge(ip, port)

def judge(ip, port):
    proxy = {'http': ip+':'+port}
    try:
        res = requests.get('https://www.baidu.com', proxies=proxy)
    except Exception:
        print('该ip:' + ip + '无效')
        return False
    else:
        if 200 <= res.status_code < 300:
            ip_list.append((ip, port))
            return True
        else:
            print('该ip:' + ip + '无效')
            return False

def get_random_ip():
    ip, port = random.choice(ip_list)
    result = judge(ip, port)
    if result:
        return ip + ':' + port
    else:
        ip_list.remove((ip, port))

if __name__ == '__main__':
    get_ip_list('https://www.xicidaili.com/wt/')
    print(ip_list)
    print(len(ip_list))

这样,我们就得到了一个可用的ip代理池,可惜,遗憾的是免费的ip代理往往不稳定,绝大多数ip都是不可用的,大家可以去尝试下。

好啦,今天的讨论到这里就结束了,大家加油。

相关文章

  • 爬虫12-使用IP代理防止被反爬

    大家好,昨天我们讨论了一下爬虫与反爬虫之间的对抗,不可谓不激烈,今天我们主要来讨论应对反爬虫中非常重要的一种手段,...

  • 网络爬虫要用到代理ip的时候有哪些?

    网络爬虫要用到代理ip的时候有哪些? 1.在爬虫的时候,被爬网站是有反爬虫机制的,如果使用一个IP反复访问一个网页...

  • 聊聊代理ip---代理ip project

    起因 学习爬虫爬取数据,不可避免就是爬虫与反爬虫的对抗. 使用代理ip作为一种反爬虫的方式还是比较有效的....

  • Python实现爬取可用代理IP

    在实现爬虫时,动态设置代理IP可以有效防止反爬虫,但对于普通爬虫初学者需要在代理网站上测试可用代理IP。由于手动测...

  • Python构建代理池

    用 Python 爬取网站内容的时候,容易受到反爬虫机制的限制,而突破反爬虫机制的一个重要措施就是使用IP代理。我...

  • 11利用python爬虫技术爬取代理ip案例

    搞爬虫第一遇到的反爬问题就是被封IP,想要继续愉快的玩耍当然是要使用代理ip了,百度“代理ip”发现都是收费的网站...

  • requests,scrapy,chrome设置代理方法

    前言 在开发爬虫时,有时候为了应对一些反爬机制比较严格的网站时,需要使用代理IP,用以隐藏自己真实IP地址或解封爬...

  • 爬虫基础系列urllib——构造请求头(3)

    爬虫与反爬虫 爬虫:自动获取网站数据的程序 反爬虫:使用技术手段防止爬虫程序爬取数据 反扒机制1 判断用户是否是浏...

  • 如何利用飞蚁代理ip池反反爬虫?

    本文关键词:飞蚁代理ip,代理ip池,反爬虫IP池 一般而言,抓取稍微正规一点的网站,都会有反爬虫的制约。反爬虫主...

  • python爬虫批量抓取ip代理

    使用爬虫抓取数据时,经常要用到多个ip代理,防止单个ip访问太过频繁被封禁。 ip代理可以从这个网站获取:http...

网友评论

      本文标题:爬虫12-使用IP代理防止被反爬

      本文链接:https://www.haomeiwen.com/subject/xmyrmqtx.html