【问题标题】:How to do multiple page scraping using Scrapy?如何使用 Scrapy 进行多页抓取?
【发布时间】:2017-03-06 17:23:09
【问题描述】:
#----\
#-----*-----\
#----/       \ 
              \
#----\         \
#-----*-------- *  <-- START
#----/         /
              / 
#----\       /
#-----*-----/     
#----/

这是我想用 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 我想在百科全书上抓取所有疾病的信息。

【问题讨论】:

    标签: python python-2.7 web-scraping scrapy


    【解决方案1】:

    您需要从“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)。

    【讨论】:

    • 谢谢!现在我已经了解了如何使用回调。许多文件中有解释,但这一下子澄清了我的疑问。顺便说一句,因为我是scrapy的新手,有没有好的网站/教程有很好的例子和解释?这将有很大帮助。再次感谢。
    • @ShubhamB。当然,网上有很多信息和教程——scrapy docs 中的官方教程非常详细。或者,有 newcoder.io 的教程 (newcoder.io/Intro-Scrape)。另一个提高你的scrapy技能的好方法是查看most voted scrapy questions on SO。谢谢。
    猜你喜欢
    • 2023-04-03
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    相关资源
    最近更新 更多