2017-03-06 30 views
1
#----\ 
#-----*-----\ 
#----/  \ 
       \ 
#----\   \ 
#-----*-------- * <-- START 
#----/  /
      /
#----\  /
#-----*-----/  
#----/ 

這裏是一個網站,我想scrapy,其中*是一個頁面,顯示---鏈接到報廢的結構。我想抓取#頁的數據。 我已經做了刮,可以從一個單一頁面#湊數據。如何使用Scrapy做多頁面報廢?

import scrapy 


class MyItem(scrapy.Item): 
    topic = scrapy.Field() 
    symptoms = scrapy.Field() 


class QuotesSpider(scrapy.Spider): 
    name = "medical" 

    allowed_domains = ['medlineplus.gov'] 
    start_urls = ['https://medlineplus.gov/ency/article/000178.htm'] 

    def parse(self, response): 
     item = MyItem() 

     item["topic"] = response.css('h1.with-also::text').extract_first() 
     item["symptoms"] = response.css("article div#section-2 li::text").extract() 

     yield item 

起始網頁是https://medlineplus.gov/encyclopedia.html 我想湊約百科全書所有疾病信息。

回答

2

您需要先從「encyclopedia.html」頁面開始,然後按照「alpha」鏈接(A-Z文章鏈接),然後對每個跟隨的頁面,按照鏈接指向文章。

您可以用CrawlSpiderLink Extractors做到這一點,但是,因爲爬行深度小,我們可以用常規Spider做到這一點:

from urlparse import urljoin # Python 2 only 

import scrapy 
from scrapy.http import Request 


class MyItem(scrapy.Item): 
    topic = scrapy.Field() 
    symptoms = scrapy.Field() 


class MedicalSpider(scrapy.Spider): 
    name = "medical" 

    allowed_domains = ['medlineplus.gov'] 
    start_urls = ['https://medlineplus.gov/encyclopedia.html'] 

    def parse(self, response): 
     for link in response.css("ul.alpha-links li a::attr(href)").extract(): 
      yield Request(urljoin(response.url, link), callback=self.parse_alpha_page) 

    def parse_alpha_page(self, response): 
     for link in response.css("ul#index li a::attr(href)").extract(): 
      yield Request(urljoin(response.url, link), callback=self.parse_page) 

    def parse_page(self, response): 
     item = MyItem() 

     item["topic"] = response.css('h1.with-also::text').extract_first() 
     item["symptoms"] = response.css("article div#section-2 li::text").extract() 

     yield item 

注意,它看起來像有一個更好的辦法獲得從MedlinePlus所需要的數據(檢查出"For Developers" page)。

+0

謝謝!現在我已經瞭解瞭如何使用回調。許多文件中都有解釋,但這一舉一動就澄清了我的疑問。順便說一句,因爲我是新來的scrapy是否有很好的網站/ scrapy的教程與良好的例子和解釋?這將有很大幫助。再次感謝。 –

+0

@ShubhamB。當然,有很多的網絡上的信息和教程 - 在scrapy文檔的官方教程是相當細緻。或者,有可能newcoder.io的教程(http://newcoder.io/Intro-Scrape/)。提高你的scrapy技能的另一個好方法是查看[最投票的scrapy問題](http://stackoverflow.com/questions/tagged/scrapy?sort=votes&pageSize=10)。謝謝。 – alecxe