Scrapy - 關注連結



說明

在本篇中,我們將學習如何提取我們感興趣的頁面連結,關注它們並從該頁面提取資料。為此,我們需要對我們上一程式碼進行如下變更:-

import scrapy
from tutorial.items import DmozItem

class MyprojectSpider(scrapy.Spider):
   name = "project"
   allowed_domains = ["dmoz.org"]
   
   start_urls = [
      "http://www.dmoz.org/Computers/Programming/Languages/Python/",
   ]
   def parse(self, response):
      for href in response.css("ul.directory.dir-col > li > a::attr('href')"):
         url = response.urljoin(href.extract())
            yield scrapy.Request(url, callback = self.parse_dir_contents)

   def parse_dir_contents(self, response):
      for sel in response.xpath('//ul/li'):
         item = DmozItem()
         item['title'] = sel.xpath('a/text()').extract()
         item['link'] = sel.xpath('a/@href').extract()
         item['desc'] = sel.xpath('text()').extract()
         yield item

以上程式碼包含以下方法:-

  • parse() - 它將提取我們感興趣的連結。

  • response.urljoin - parse() 方法將使用此方法構建一個新的 URL 並提供一個新的請求,稍後將將其傳送給回撥函式。

  • parse_dir_contents() - 這是一個回撥函式,它將實際抓取我們感興趣的資料。

Scrapy 在這裡使用一個回撥機制來關注連結。利用此機制,可以設計出更大的爬蟲,還可以關注我們感興趣的連結,以便從不同的網頁中抓取所需資料。常規方法將是回撥方法,它將提取項,尋找連結以關注下一頁,然後為相同的回撥提供一個請求。

以下示例產生一個迴圈,它將關注連結到下一頁。

def parse_articles_follow_next_page(self, response):
   for article in response.xpath("//article"):
      item = ArticleItem()
    
      ... extract article data here

      yield item

   next_page = response.css("ul.navigation > li.next-page > a::attr('href')")
   if next_page:
      url = response.urljoin(next_page[0].extract())
      yield scrapy.Request(url, self.parse_articles_follow_next_page)
廣告
© . All rights reserved.