Spider框架02总结【翻页爬取的meta理解,POST的请求,CrawlSpider类的用法, 中间件的使用】

meta参数的理解及用法:

import scrapy
from Tencent.items import TencentItem


class TencentSpider(scrapy.Spider):
    name = 'tencent'
    allowed_domains = ['tencent.com']
    start_urls = ['http://hr.tencent.com/position.php?&start=0#a']

    def __init__(self, name=None, **kwargs):
        super().__init__(name=None, **kwargs)

    def parse(self, response):
        # 1.确定目标   建模
        # 2.制作爬虫
        # 2.1提取当前页的数据
        tr_list = response.xpath("//tr[contains(@class, 'odd')]|//tr[contains(@class,'even')]")
        host = "http://hr.tencent.com/"
        for tr in tr_list:
            # 创建模型类对象保存数据
            item = TencentItem()
            item['url'] = host+tr.xpath("./td[1]/a/@href").extract_first()
            item['name'] = tr.xpath("./td[1]/a/text()").extract_first()
            item['genre'] = tr.xpath("./td[2]/text()").extract_first()
            item['number'] = tr.xpath("./td[3]/text()").extract_first()
            item['address'] = tr.xpath("./td[4]/text()").extract_first()
            item['pub_date'] = tr.xpath("./td[5]/text()").extract_first()

            # 2.2保存
            # yield item
            # 创建详情页面的请求
            yield scrapy.Request(url=item['url'], callback=self.parse_detail, meta={'itcast': item})
            # 实例Request对象时将基本页的item信息保存到meta属性当中,当该请求发送后返回response对象时会将该
            # Resquest实例对象复制给Response中的一个属性,该response实例会传给parse函数,所以在提取下一页的信息时,
            # 也能获取到该item的信息,,,从而当以基本信息和详情信息的对应(具体查看框架的Response类,Request的源码)
        # 2.3获取下一页
        next_url = host + response.xpath('//a[@id="next"]/@href').extract_first()
        # 2.4回调
        yield scrapy.Request(next_url, callback=self.parse)
        # 3.保存数据

    def parse_detail(self, response):
        # 获取item
        item = response.meta['itcast']
        # 获取招聘
        item['duty'] = ''.join(response.xpath("//tr[3]/td/ul/li/text()").extract())
        item['require'] = ''.join(response.xpath("//tr[4]/td/ul/li/text()").extract())

        yield item
示例Code

中间件设置代理,随机User-Agent方法

python3转码

from Douban.settings import USER_AGENT_LIST

class RandomUserAgent(object):
    def process_request(self, request, spider):
        # 设置user-agent
        request.headers['User-Agent'] = random.choice(USER_AGENT_LIST)
        # 定义代理ip和密码
        proxy = {"ip_port": "121.41.8.23:16816", "user_passwd": "morganna_mode_g:ggc22qxp"}
        # b64   认证编码格式
        usr_pwd = base64.b64encode(bytes(proxy["user_passwd"], encoding='utf-8'))
        # 认证
        request.headers['Proxy-Authorization'] = "Basic " + usr_pwd.decode()
        # 设置代理
        request.meta['proxy'] = 'http://' + proxy['ip_port']
python3Code

python2无需转码

from scrapy import signals
# 导入编码模块
import base64

class TencentSpiderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Response, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class Proxy(object):

    def process_request(self,request,spider):
        # 获取代理ip
        proxy = {"ip_port": "use", "user_passwd": "morganna_mode_g:ggc22qxp"}
        # 对账号密码进行加密
        b64_user_pwd = base64.b64encode(proxy['user_passwd'])

        # 认证
        request.headers['Proxy-Authorization'] = "Basic " + b64_user_pwd
        # 设置代理ip
        request.meta['proxy'] = 'http://' + proxy['ip_port']
python2Code

User-Agent

# 随机分配user-agent USER_AGENT_LIST 为user-agent列表
from Douban.settings import USER_AGENT_LIST

class RandomUserAgent(object):
    def process_request(self, request, spider):
        # 设置user-agent
        request.headers['User-Agent'] = random.choice(USER_AGENT_LIST)
        # 定义代理ip和密码
        proxy = {"ip_port": "121.41.8.23:16816", "user_passwd": "morganna_mode_g:ggc22qxp"}
        # b64   认证编码格式
        usr_pwd = base64.b64encode(bytes(proxy["user_passwd"], encoding='utf-8'))
        # 认证
        request.headers['Proxy-Authorization'] = "Basic " + usr_pwd.decode()
        # 设置代理
        request.meta['proxy'] = 'http://' + proxy['ip_port']
View Code

POST提交

重写spider的start_requests方法

创建scrapy.FormRequest()实例传递参数

# -*- coding: utf-8 -*-
import scrapy


class RenrenSpider(scrapy.Spider):
    name = 'renren'
    allowed_domains = ['renren.com']
    start_urls = ['http://www.renren.com/PLogin.do']

    def start_requests(self):
        url = self.start_urls[0]
        # 重写start_requests方法
        # 设置账号密码
        data = {
            "email": "17173805860",
            "password": "1qaz@WSX3edc"
        }
        # 发送请求
        yield scrapy.FormRequest(url=url, formdata=data, callback=self.parse)


    def parse(self, response):
        with open('renren.html', 'w') as f:
            f.write(response.body.decode('utf-8'))
示例Code

利用scrapy.FormRequest.from_response()方法自动找对应的表单提交

import scrapy


class Renren2Spider(scrapy.Spider):
    name = 'renren2'
    allowed_domains = ['renren.com']
    start_urls = ['http://renren.com/']

    def parse(self, response):
        # 设置账号密码
        data = {
            "email": "17173805860",
            "password": "1qaz@WSX3edc"
        }
        # 发送请求传递参数  response callback formdata
        yield scrapy.FormRequest.from_response(response=response, callback=self.k_open_file, formdata=data)

    def k_open_file(self, response):
        with open('renren2.html', 'wb') as f:
            f.write(response.body)
示例Code

CrawlSpider 

通过下面的命令可以快速创建 CrawlSpider模板 的代码:

scrapy genspider -t crawl 爬虫名字 允许的域

它是Spider的派生类,Spider类的设计原则是只爬取start_url列表中的网页,而CrawlSpider类定义了一些规则(rule)来提供跟进link的方便的机制,从爬取的网页中获取link并继续爬取的工作更适合。

class CrawlSpider(Spider):
    rules = ()
    def __init__(self, *a, **kw):
        super(CrawlSpider, self).__init__(*a, **kw)
        self._compile_rules()

    #首先调用parse()来处理start_urls中返回的response对象
    #parse()则将这些response对象传递给了_parse_response()函数处理,并设置回调函数为parse_start_url()
    #设置了跟进标志位True
    #parse将返回item和跟进了的Request对象    
    def parse(self, response):
        return self._parse_response(response, self.parse_start_url, cb_kwargs={}, follow=True)

    #处理start_url中返回的response,需要重写
    def parse_start_url(self, response):
        return []

    def process_results(self, response, results):
        return results

    #从response中抽取符合任一用户定义'规则'的链接,并构造成Resquest对象返回
    def _requests_to_follow(self, response):
        if not isinstance(response, HtmlResponse):
            return
        seen = set()
        #抽取之内的所有链接,只要通过任意一个'规则',即表示合法
        for n, rule in enumerate(self._rules):
            links = [l for l in rule.link_extractor.extract_links(response) if l not in seen]
            #使用用户指定的process_links处理每个连接
            if links and rule.process_links:
                links = rule.process_links(links)
            #将链接加入seen集合,为每个链接生成Request对象,并设置回调函数为_repsonse_downloaded()
            for link in links:
                seen.add(link)
                #构造Request对象,并将Rule规则中定义的回调函数作为这个Request对象的回调函数
                r = Request(url=link.url, callback=self._response_downloaded)
                r.meta.update(rule=n, link_text=link.text)
                #对每个Request调用process_request()函数。该函数默认为indentify,即不做任何处理,直接返回该Request.
                yield rule.process_request(r)

    #处理通过rule提取出的连接,并返回item以及request
    def _response_downloaded(self, response):
        rule = self._rules[response.meta['rule']]
        return self._parse_response(response, rule.callback, rule.cb_kwargs, rule.follow)

    #解析response对象,会用callback解析处理他,并返回request或Item对象
    def _parse_response(self, response, callback, cb_kwargs, follow=True):
        #首先判断是否设置了回调函数。(该回调函数可能是rule中的解析函数,也可能是 parse_start_url函数)
        #如果设置了回调函数(parse_start_url()),那么首先用parse_start_url()处理response对象,
        #然后再交给process_results处理。返回cb_res的一个列表
        if callback:
            #如果是parse调用的,则会解析成Request对象
            #如果是rule callback,则会解析成Item
            cb_res = callback(response, **cb_kwargs) or ()
            cb_res = self.process_results(response, cb_res)
            for requests_or_item in iterate_spider_output(cb_res):
                yield requests_or_item

        #如果需要跟进,那么使用定义的Rule规则提取并返回这些Request对象
        if follow and self._follow_links:
            #返回每个Request对象
            for request_or_item in self._requests_to_follow(response):
                yield request_or_item

    def _compile_rules(self):
        def get_method(method):
            if callable(method):
                return method
            elif isinstance(method, basestring):
                return getattr(self, method, None)

        self._rules = [copy.copy(r) for r in self.rules]
        for rule in self._rules:
            rule.callback = get_method(rule.callback)
            rule.process_links = get_method(rule.process_links)
            rule.process_request = get_method(rule.process_request)

    def set_crawler(self, crawler):
        super(CrawlSpider, self).set_crawler(crawler)
        self._follow_links = crawler.settings.getbool('CRAWLSPIDER_FOLLOW_LINKS', True)
CrawlSpider_source_Code

Crawlspider与Spider类的区别

  • 不能重写parse方法
    • 原因: CrawlSpider类在parse方法中实现了自身逻辑
  • 如何解析起始url对应的响应
    • ①重写parse_start_url
    • ②parse_start_url必须返回数据或请求的列表

crapySpider类的优缺点

  • 1.优点: 适合整站爬取 爬取效率高
  • 2.缺点: 无法通过meta进行参数传递,现在的你无法碰到request,一个2货(Rule)管理你的request

rules

提取理解

CrawlSpider使用rules来决定爬虫的爬取规则,并将匹配后的url请求提交给引擎。所以在正常情况下,CrawlSpider不需要单独手动返回请求了。

在rules中包含一个或多个Rule对象,每个Rule对爬取网站的动作定义了某种特定操作,比如提取当前相应内容里的特定链接,是否对提取的链接跟进爬取,对提交的请求设置回调函数等。

如果多个rule匹配了相同的链接,则根据规则在本集合中被定义的顺序,第一个会被使用。

class scrapy.spiders.Rule(
        link_extractor,
        callback = None,
        cb_kwargs = None,
        follow = None,
        process_links = None,
        process_request = None
)


link_extractor:是一个Link Extractor对象,用于定义需要提取的链接。

callback: 从link_extractor中每获取到链接时,参数所指定的值作为回调函数,该回调函数接受一个response作为其第一个参数。

注意:当编写爬虫规则时,避免使用parse作为回调函数。由于CrawlSpider使用parse方法来实现其逻辑,如果覆盖了 parse方法,crawl spider将会运行失败。

follow:是一个布尔(boolean)值,指定了根据该规则从response提取的链接是否需要跟进如果callback为None,follow 默认设置为True ,否则默认为False。

process_links:指定该spider中哪个的函数将会被调用,从link_extractor中获取到链接列表时将会调用该函数。该方法主要用来过滤(link)。

process_request:指定该spider中哪个的函数将会被调用, 该规则提取到每个request时都会调用该函数。 (用来过滤request)

LinkExtractors

class scrapy.linkextractors.LinkExtractor

Link Extractors 的目的很简单: 提取链接。

每个LinkExtractor有唯一的公共方法是 extract_links(),它接收一个 Response 对象,并返回一个 scrapy.link.Link 对象。

Link Extractors要实例化一次,并且 extract_links 方法会根据不同的 response 调用多次提取链接。

class scrapy.linkextractors.LinkExtractor(
    allow = (),
    deny = (),
    allow_domains = (),
    deny_domains = (),
    deny_extensions = None,
    restrict_xpaths = (),
    tags = ('a','area'),
    attrs = ('href'),
    canonicalize = True,
    unique = True,
    process_value = None
)

主要参数:

allow:满足括号中“正则表达式”的URL会被提取,如果为空,则全部匹配。

deny:满足括号中“正则表达式”的URL一定不提取(优先级高于allow)。

allow_domains:会被提取的链的域名。

deny_domains:一定不会被提取链接的域名。

restrict_xpaths:使用xpath表达式,和allow共同作用过滤链接。(限定allow的匹配范围i)

Logging

Scrapy提供了log功能,可以通过 logging 模块使用。

可以修改配置文件settings.py,任意位置添加下面两行,效果会清爽很多。

LOG_FILE = "TencentSpider.log"
LOG_LEVEL = "INFO"

Log levels

Scrapy提供5层logging级别:

CRITICAL - 严重错误(critical)
ERROR - 一般错误(regular errors)
WARNING - 警告信息(warning messages)
INFO - 一般信息(informational messages)
DEBUG - 调试信息(debugging messages)

logging设置

通过在setting.py中进行以下设置可以被用来配置logging:

LOG_ENABLED 默认: True,启用logging
LOG_ENCODING 默认: 'utf-8',logging使用的编码
LOG_FILE 默认: None,在当前目录里创建logging输出文件的文件名
LOG_LEVEL 默认: 'DEBUG',log的最低级别
LOG_STDOUT 默认: False 如果为 True,进程所有的标准输出(及错误)将会被重定向到log中。例如,执行 print "hello" ,其将会在Scrapy log中显示。

  

 

posted @ 2017-08-19 19:25  凯哥吧  阅读(775)  评论(0)    收藏  举报