Scrapy學習第六課

python爬蟲框架scrapy學習第六課

知識點:start_requests()

  • 函數解釋:該方法必須返回一個可迭代對象(iterable)。該對象包含了spider用於爬取的第一個Request。當spider啓動爬取並且未制定URL時,該方法被調用。 當指定了URL時,make_requests_from_url() 將被調用來創建Request對象。 該方法僅僅會被Scrapy調用一次,因此您可以將其實現爲生成器。該方法的默認實現是使用 start_urls 的url生成Request。

  • 源碼分析:針對start_urls中的每一個url 發起resquest請求。當start_urls中有多個鏈接時,逐步發起請求。

def start_requests(self):
    for url in self.start_urls:
        yield self.make_requests_from_url(url)
def make_requests_from_url(self, url):
    return Request(url, dont_filter=True)
  • 代碼演示
    – 不顯示引用start_requests展示爬取順序和爬取結果
import scrapy

class KrSpider(scrapy.Spider):
    name = 'kr'
    allowed_domains = ['ifeng.com']
    start_urls = [
        'http://news.ifeng.com/a/20181225/60208881_0.shtml',
        'http://news.ifeng.com/a/20181225/60208818_0.shtml',
        'http://news.ifeng.com/a/20181225/60208776_0.shtml'
    ]
    
    def parse(self, response):
        filename = "test.html"
        title = response.xpath('//h1[@id="artical_topic"]/text()').extract()
        print(title)
        

start_urls中包含3個url,按照函數釋義,會按照順序逐步被調用爬取數據,觀其結果可知,順序和結果是正確的。
在這裏插入圖片描述
–修改start_requests的內容,通過爬蟲結果,證實該函數在發起爬取過程中被調用

import scrapy


class KrSpider(scrapy.Spider):
    name = 'kr'
    allowed_domains = ['ifeng.com']
    start_urls = [
        'http://news.ifeng.com/a/20181225/60208881_0.shtml',
        'http://news.ifeng.com/a/20181225/60208818_0.shtml',
        'http://news.ifeng.com/a/20181225/60208776_0.shtml'
    ]

    def start_requests(self):
       yield scrapy.Request(url=self.start_urls[0], callback=self.parse)

    def parse(self, response):
        filename = "test.html"
        title = response.xpath('//h1[@id="artical_topic"]/text()').extract()
        print(title)
        

在這裏插入圖片描述

從結果中可知,顯示的start_requests函數被調用,覆蓋原有的功能。

  • 代碼修改:get變post…該功能暫未學習,後續補充。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章