关于爬虫:详解如何应对反爬技术

3次阅读

共计 7432 个字符,预计需要花费 19 分钟才能阅读完成。

一、反爬的基本概念
反爬虫技术是一种应用技术手段避免爬虫的办法。
二、反爬的基本原理及用到的技术手段

上图的意思:
爬虫方 :假如咱们编写了一个爬虫程序,咱们剖析了网络申请以便编写程序,用 Scrapy 框架写了一个爬虫,执行程序。
反爬方 :网站出于本身权利的保障,想辨认咱们的爬虫程序,并限度咱们的拜访。为了实现上述性能,网站须要做到监控用户对网站的操作,在监控的时候,网站在某个时间段不停地被一个 IP 地址大规模的拜访,User_agent(解释如下,摘自百度百科) 是 Python,想封 IP 吧,又避免误伤,所以只好限度拜访这个 IP。(User_agent,简称 UA,中文:用户代理。User_agent 是一个非凡字符串头,使得服务器可能辨认客户应用的操作系统及版本、CPU 类型、浏览器及版本、浏览器渲染引擎、浏览器语言、浏览器插件等。)
爬虫方 :我方察觉到 IP 被限度拜访,就在 Firefox、Chrome 等浏览器上找到 User_agent, 将 User_agent 退出到爬虫程序里去。而后找一个 IP 池,在 IP 池里拿一个 IP 进行拜访。或者,我方还能够禁用 Cookie,避免网站辨认出用户的 ID。
反爬方 :这时,网站发现还是会有大规模的拜访(大量的爬虫),就设置了一种策略,数据必须登录能力拜访。
爬虫方 :咱们的应答策略是,注册账号,每次申请时带着 Cookie 或者 Token。
反爬方 :网站发现还是不行,就规定要加为好友后能力拜访。
爬虫方 :这时咱们就注册多个账号,让它们不停的加好友,这样就能获取到大量的信息。
反爬方 :发现爬取过于频繁,进一步限度 IP 的拜访。
爬虫方 :让爬虫模拟人为解决的申请,比如说,每 3 分钟爬取一次。
反爬方 :网站发现这个 IP 很法则,每 3 分钟申请一次,很有可能是个爬虫。所以又做出进一步的限度,弹出验证码,要求辨认验证码能力登录。
爬虫方 :我方就依照要求辨认验证码。
反爬方 :网站利用动静网站技术(Ajax)减少动静网站,数据通过 Js 动静加载。
爬虫方 :用 Selenium 操控浏览器,就能够拿到动静网站的数据。
反爬方 :发现 IP 只申请 Html 不申请 Image、Js、Css,很容易就辨认出该 IP 是爬虫。
爬虫方 :这时用 Selenium 就无奈做到了,然而,用户和 Selenium 一样都是通过浏览器发动申请的。网站如果要进一步限度拜访,无异于限度掉一些用户的拜访。这样做是有危险的,因为网站是要有盈利的,如果没有盈利,那也就没有了存在的必要。到了前期,网站的用于反爬的老本也会越来越高。
综上,反爬是不可能战败爬虫的。
爬虫爬取网站次要用到的技术手段是:
1、配置 User_agent。
2、注册账号,登录时辨认验证码。
3、用 Selenium 操控浏览器。
三、爬虫伎俩之随机切换 User_agent
随机切换 User_agent 利用到 Github 上一个我的项目,先 workon 虚拟环境
pip install fake-useragent==0.1.11(它实际上是本人外部保护了一个 URL:fake-useragent(0.1.11),这个 URL 里有所有保护的 User_agent,如果有须要能够拿着这个 URL 将所有的 User_agent 取下来)
接下来在 middlewares.py 里退出以下代码:

class RandomUserAgentMiddlware(object):
    #随机更换 user-agent
    def __init__(self, crawler):
        super(RandomUserAgentMiddlware, self).__init__()
        self.ua = UserAgent()
        self.ua_type = crawler.settings.get("RANDOM_UA_TYPE", "random")

    @classmethod
    def from_crawler(cls, crawler):
        return cls(crawler)

    def process_request(self, request, spider):
        def get_ua():
            return getattr(self.ua, self.ua_type)

        request.headers.setdefault('User-Agent', get_ua())

再在 settings.py 里配置 middlewares:

DOWNLOADER_MIDDLEWARES = {
   # 'ArticleSpider.middlewares.ArticlespiderDownloaderMiddleware': 543,
    'scrapy.downloadermiddlewares.useragent.RandomUserAgentMiddlware':2,
}

四、爬虫伎俩之设置 IP 代理
首先咱们须要晓得,IP 是动态分配的,当咱们应用本人的 Ip 爬取网页速度过快的时候,网站会辨认到,并有可能有禁用咱们本人的 IP,这时候只需重启光猫和路由器即可刷新网络,再爬取信息了。但个别不要频繁的爬取页面,因为应用咱们本人的 IP 是最好最不容易被辨认的。
IP 代理的原理:当应用爬虫爬取网页时,如果咱们没有代理服务器代理 IP, 咱们就间接本人在网站浏览,这时如果爬虫被辨认了,就会间接禁用掉咱们本人的 IP。而如果应用代理服务器代理 IP 的话,咱们是通过代理服务器在网站上爬取信息,这时网站顶多禁用掉代理服务器,咱们本人的 IP 就相当于被暗藏了起来,就不会裸露咱们本人的 IP。
上面,设置一下 IP 代理,爬取西刺网上的 IP 信息。

import requests
from scrapy.selector import Selector
import MySQLdb

conn = MySQLdb.connect(host="127.0.0.1", user="root", passwd="root", db="article_spider", charset="utf8")
cursor = conn.cursor()


def crawl_ips():
    #爬取西刺的收费 ip 代理
    headers = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0"}
    for i in range(1568):
        re = requests.get("http://www.xicidaili.com/nn/{0}".format(i), headers=headers)

        selector = Selector(text=re.text)
        all_trs = selector.css("#ip_list tr")


        ip_list = []
        for tr in all_trs[1:]:
            speed_str = tr.css(".bar::attr(title)").extract()[0]
            if speed_str:
                speed = float(speed_str.split("秒")[0])
            all_texts = tr.css("td::text").extract()

            ip = all_texts[0]
            port = all_texts[1]
            proxy_type = all_texts[5]

            ip_list.append((ip, port, proxy_type, speed))

        for ip_info in ip_list:
            cursor.execute("insert proxy_ip(ip, port, speed, proxy_type) VALUES('{0}','{1}', {2},'HTTP')".format(ip_info[0], ip_info[1], ip_info[3]
                )
            )

            conn.commit()


class GetIP(object):
    def delete_ip(self, ip):
        #从数据库中删除有效的 ip
        delete_sql = """delete from proxy_ip where ip='{0}'""".format(ip)
        cursor.execute(delete_sql)
        conn.commit()
        return True

    def judge_ip(self, ip, port):
        #判断 ip 是否可用
        http_url = "http://www.baidu.com"
        proxy_url = "http://{0}:{1}".format(ip, port)
        try:
            proxy_dict = {"http":proxy_url,}
            response = requests.get(http_url, proxies=proxy_dict)
        except Exception as e:
            print ("invalid ip and port")
            self.delete_ip(ip)
            return False
        else:
            code = response.status_code
            if code >= 200 and code < 300:
                print ("effective ip")
                return True
            else:
                print  ("invalid ip and port")
                self.delete_ip(ip)
                return False


    def get_random_ip(self):
        #从数据库中随机获取一个可用的 ip
        random_sql = """
              SELECT ip, port FROM proxy_ip
            ORDER BY RAND()
            LIMIT 1
            """
        result = cursor.execute(random_sql)
        for ip_info in cursor.fetchall():
            ip = ip_info[0]
            port = ip_info[1]

            judge_re = self.judge_ip(ip, port)
            if judge_re:
                return "http://{0}:{1}".format(ip, port)
            else:
                return self.get_random_ip()



# print (crawl_ips())
if __name__ == "__main__":
    get_ip = GetIP()
    get_ip.get_random_ip()

五、爬虫伎俩之通过云打码实现验证码登录

import json
import requests

class YDMHttp(object):
    apiurl = 'http://api.yundama.com/api.php'
    username = ''password =''
    appid = ''appkey =''

    def __init__(self, username, password, appid, appkey):
        self.username = username
        self.password = password
        self.appid = str(appid)
        self.appkey = appkey

    def balance(self):
        data = {'method': 'balance', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey}
        response_data = requests.post(self.apiurl, data=data)
        ret_data = json.loads(response_data.text)
        if ret_data["ret"] == 0:
            print ("获取残余积分", ret_data["balance"])
            return ret_data["balance"]
        else:
            return None

    def login(self):
        data = {'method': 'login', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey}
        response_data = requests.post(self.apiurl, data=data)
        ret_data = json.loads(response_data.text)
        if ret_data["ret"] == 0:
            print ("登录胜利", ret_data["uid"])
            return ret_data["uid"]
        else:
            return None

    def decode(self, filename, codetype, timeout):
        data = {'method': 'upload', 'username': self.username, 'password': self.password, 'appid': self.appid, 'appkey': self.appkey, 'codetype': str(codetype), 'timeout': str(timeout)}
        files = {'file': open(filename, 'rb')}
        response_data = requests.post(self.apiurl, files=files, data=data)
        ret_data = json.loads(response_data.text)
        if ret_data["ret"] == 0:
            print ("辨认胜利", ret_data["text"])
            return ret_data["text"]
        else:
            return None

def ydm(file_path):
    username = 'da_ge_da1'
    # 明码
    password = 'dageda'
    # 软件ID,开发者分成必要参数。登录开发者后盾【我的软件】取得!appid = 3129
    # 软件密钥,开发者分成必要参数。登录开发者后盾【我的软件】取得!appkey = '40d5ad41c047179fc797631e3b9c3025'
    # 图片文件
    filename = 'en_captcha.jpg'
    # 验证码类型,# 例:1004 示意 4 位字母数字,不同类型免费不同。请精确填写,否则影响识别率。在此查问所有类型 http://www.yundama.com/price.html
    codetype = 5000
    # 超时工夫,秒
    timeout = 60
    # 查看

    yundama = YDMHttp(username, password, appid, appkey)
    if (username == 'username'):
        print('请设置好相干参数再测试')
    else:
        # 开始辨认,图片门路,验证码类型 ID,超时工夫(秒),辨认后果
        return yundama.decode(file_path, codetype, timeout);

if __name__ == "__main__":
    # 用户名
    username = 'da_ge_da1'
    # 明码
    password = 'dageda'
    # 软件ID,开发者分成必要参数。登录开发者后盾【我的软件】取得!appid = 3129
    # 软件密钥,开发者分成必要参数。登录开发者后盾【我的软件】取得!appkey = '40d5ad41c047179fc797631e3b9c3025'
    # 图片文件
    filename = 'D:/ImoocProjects/python_scrapy/coding-92/ArticleSpider/tools/en_captcha.gif'
    # 验证码类型,# 例:1004 示意 4 位字母数字,不同类型免费不同。请精确填写,否则影响识别率。在此查问所有类型 http://www.yundama.com/price.html
    codetype = 5000
    # 超时工夫,秒
    timeout = 60
    # 查看
    if (username == 'username'):
        print ('请设置好相干参数再测试')
    else:
        # 初始化
        yundama = YDMHttp(username, password, appid, appkey)

        # # 登陆云打码
        # uid = yundama.login();
        # print('uid: %s' % uid)
        #
        # # 登陆云打码
        # uid = yundama.login();
        # print ('uid: %s' % uid)
        #
        # # 查问余额
        # balance = yundama.balance();
        # print ('balance: %s' % balance)

        # 开始辨认,图片门路,验证码类型 ID,超时工夫(秒),辨认后果
        code = yundama.decode("en_captcha.gif", 5000, 60)
        print(code)

六、爬虫伎俩之 Cookie 禁用
在 settings.py 里有这样一行代码:
COOKIES_ENABLED = False
将 COOKIES_ENABLED 设置为 False,Cookie 就被禁用掉了,然而对于像知乎那样的须要登录能力拜访的网站,设置为 False 就不能登录了,所以在知乎爬虫页面要将 settings.py 里的 COOKIES_ENABLED 笼罩掉,通过查看源码失去须要在知乎爬虫页面设置如下代码:

custom_settings = {"COOKIES_ENABLED": True}

七、爬虫伎俩之主动限速
比方每 10 秒钟下载一次,settings.py 代码如下:

DOWNLOAD_DELAY = 10
AUTOTHROTTLE_ENABLED = True
AUTOTHROTTLE_MAX_DELAY = 10

八、爬虫伎俩之 Selenium 模仿登录
上面用 Selenium 模仿登录:

from selenium import webdriver
from scrapy.selector import Selector

browser = webdriver.Chrome(executable_path="D:/Temp/chromedriver.exe")

browser.get("https://www.zhihu.com/#signin")

browser.find_element(".view-signin input[name='account']").send_keys("18782902568")
browser.find_element(".view-signin input[name='password']").send_keys("admin125")

browser.find_element(".view-signin button.sign-button").click()
browser.quit()

以上就是我对于应答反爬的技术详解啦~

正文完
 0