【问题标题】:Scrapy crawl web with many duplicated element class name具有许多重复元素类名称的 Scrapy 爬网
【发布时间】:2020-08-29 22:54:26
【问题描述】:

我是 Scrapy 的新手,正在尝试抓取网页,但 HTML 元素由许多具有重复类名的 DIV 组成,例如。

<section class= "pi-item pi-smart-group pi-border-color">

<section class="pi-smart-group-head">
    <h3 class = "pi-smart-data-label pi-data-label pi-secondary-font pi-item-spacing">
</section>

    <section class= "pi-smart-group-body">
        <div class="pi-smart-data-value pi-data-value pi-font pi-item-spacing">
            <a href="abc" title="!! What I want !!"> </a>
        </div>
    </section>
</section>

我的问题是这个结构对许多其他元素重复,当我使用 response.css 时,我会得到多个我不想要的元素

(基本上我想从https://pokemon.fandom.com/wiki/Bulbasaur抓取每个口袋妖怪的“类型”、“物种”和“能力”,我已经完成了所有口袋妖怪的获取网址,但一直在从每个口袋妖怪获取信息)

【问题讨论】:

    标签: scrapy web-crawler


    【解决方案1】:

    您可以将 XPath 表达式与属性文本一起使用:

    abilities = response.xpath('//h3[a[.="Abilities"]]/following-sibling::div[1]/a/text()').getall()
    species = response.xpath('//h3[a[.="Species"]]/following-sibling::div[1]/text()').get()
    

    【讨论】:

      【解决方案2】:

      我已经尝试为你做这个scrapy项目并得到了结果。我看到的问题是您使用了 CSS。您可以使用它,但使用 Xpath 选择器要有效得多。您可以更灵活地选择所需的特定标签。这是我为您编写的代码。请记住,这段代码只是我为了得到你的结果而快速完成的。它可以工作,但我是这样做的,所以你很容易理解它,因为你是scrapy的新手。如果有帮助请告诉我

      import scrapy
      
      
      class PokemonSpiderSpider(scrapy.Spider):
          name = 'pokemon_spider'
          start_urls = ['https://pokemon.fandom.com/wiki/Bulbasaur']
      
          def parse(self, response):
              pokemon_type = response.xpath("(//div[@class='pi-data-value pi-font'])[1]/a/@title")
              pokemon_species = response.xpath('//div[@data-source="species"]//div/text()')
              pokemon_abilities = response.xpath('//div[@data-source="ability"]/div/a/text()')
      
              yield {
                  'pokemon type': pokemon_type.extract(),
                  'pokemon species': pokemon_species.extract(),
                  'pokemon abilities': pokemon_abilities.extract()
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-11
        • 1970-01-01
        • 2017-02-10
        • 1970-01-01
        相关资源
        最近更新 更多