Python 分布式爬虫框架 Scrapy 7-5 scrapy实现ip代理池

到目前为止,cnblogs仍然只能获取60条信息。

家里的ip是动态分配的,重启路由器可能导致ip变化。阿里云是静态的,亚马逊是动态的。

实际上,代理ip会减慢爬取速度,所以我们尽量限制我们本机的爬取速度。

正常情况下:

有了ip代理:

ip代理有高匿与普通之别。高匿是说代理服务器完全不知道我们本机的ip,而普通是说代理服务器可能会将本机ip带过去。

在scrapy中实现ip代理十分简单,之前写的RandomUserAgentMiddlware中的process_request会处理每一个request,我们只需要在该函数的最后加一句:

request.meta["proxy"] = "http://60.167.159.236:808"

后面的ip代理是哪里来的呢?是在西刺免费代理IP中找的。

当然了,我们如果要实现一个ip代理池,是还有其他工作要做的。也就是说,既然要实现ip代理,自然不能只有一个ip,我们需要一个代理池,以此实现每次随机取出一个ip代理。如何实现?很简单,我们爬取西刺这个网站就好了。

注释掉:

# request.meta["proxy"] = "http://60.167.159.236:808"

新建一个名为tools的package:

新建一个脚本crawl_xici_ip.py,并安装requests:

pip install -i https://pypi.douban.com/simple requests

编辑crawl_xici_ip.py:

import requests
from scrapy.selector import Selector
import MySQLdb

conn = MySQLdb.connect(host="127.0.0.1", user="root", passwd="", db="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(2073):
        re = requests.get("https://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_first()
            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:
            sql = "insert proxy_ip(ip, port, speed, proxy_type) VALUES('{0}', '{1}', {2}, '{3}')".format(
                ip_info[0], ip_info[1], ip_info[3], ip_info[2]
            )
            try:
                # 执行sql语句
                cursor.execute(sql)
                # 提交到数据库执行
                conn.commit()
            except:
                # Rollback in case there is any error
                conn.rollback()

            conn.commit()

        print("---------------{0} done---------------".format(i))


if __name__ == "__main__":
    crawl_ips()

这里用到了requests库,和python操作mysql的知识(注意sql语句,对于字符串类型,要有单引号)。

我们之前直接对response做了selector,实际上,这是因为response本身包装了Scrapy的Selector,这里我们直接使用了Selector。

运行之前,新建一个表proxy_ip(可以不设主键,或者以ip为第一主键,port为第二主键):

运行。

上面完成了数据爬取,下面还要实现ip代理的获取。是从数据库中获取,如何获取呢?可以使用下面这条sql语句:

SELECT ip, port FROM proxy_ip
ORDER BY RAND()
LIMIT 1

可以在Navicat中进行测试:

所以,再添加一个类:

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, proxy_type):
        # 判断ip是否可用
        http_url = "http://www.baidu.com"
        proxy_url = "{0}://{1}:{2}".format(proxy_type, 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, proxy_type 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]
            proxy_type = ip_info[2]

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

将入口调用改为(要写在__main__之下,否则在import的时候,会执行这些逻辑):

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

调试一下,成功之后,回到middlewares.py,引入刚刚的类:

from tools.crawl_xici_ip import GetIP

添加一个新的middleware类:

class RandomProxyMiddleware(object):
    # 动态设置ip代理
    def process_request(self, request, spider):
        get_ip = GetIP()
        request.meta["proxy"] = get_ip.get_random_ip()

此外有一个开源的库——scrapy-proxies,这是一款scrapy的插件,比我们的功能强大得多,代码只有一个文件。它就是定义了一个middleware,但是是通过settings进行读取的,是读文件,这一点不如我们从数据库中操作优。可以拿着进行改造。

此外,scrapy官方有一个scrapy-crawlera项目,这让我们动态IP的配置更加简单,但是需要收费。

此外是tor,洋葱浏览器,洋葱网络实际上是对我们的网络进行了很多层的包装。当我们的请求经过这个洋葱网络,它就会做多次的转发,达到了匿名效果,黑客多用。但这个需要VPN,一个敏感话题。

按需要,决定是否在settings.py中配置:

'Spoder.middlewares.RandomProxyMiddleware':605
发布了101 篇原创文章 · 获赞 26 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/liujh_990807/article/details/100149898