Scrapy splash-循环将所有值仅保存到一项

时间:2019-03-30 00:25:29

标签: python web-scraping scrapy

我将Scrapy与Splash一起使用来抓取基于Javascript的网站的值。代码工作正常,蜘蛛抓取所有有趣的值。问题在于它将所有这些值仅保存到一项。

class Spider(CrawlSpider):
    name = "test"
    start_urls = ["http://example.com/results"]

    rules = (
        Rule(LinkExtractor(restrict_xpaths = ('//div[contains(@class, "products")]'), ),
             callback="parse",
             follow=False),)

    def start_requests(self):
       for url in self.start_urls:

           yield SplashRequest(url,callback=self.parse, endpoint='render.html', args={'wait':25.5})

    def parse(self, response):

       product_list = response.xpath('//div[contains(@class, "products")]').extract()

       for items in product_list:
          item=TestItem()
          item['CompanyName'] = response.xpath('').extract()
          item['Revenue'] = response.xpath('').extract()
          item['Tag'] = response.xpath('').extract()
          yield item

我看不到上面的代码有什么问题。我所有的物品都放在一格之内。但是有一些包含这些项目的div div。网站在一页上显示了很多结果,我需要从中获取这些价值。例如,在div products中,有10个不同的div包含上述项目。

输出如下:

CompanyName,Tagline,Revenue
XcompanyName, YcomapnyName, ZCompanyName
Xtagline, Ytagline, Ztagline
Xrevenue, Yrevenue, Zrevenue

我希望它是:

CompanyName,Tagline,Revenue
XcompanyName, Ytagline, Zrevenue
YcompanyName, Ytagline, Yrevenue
ZcompanyName, Ztagline, Zrevenue

网站CSS:

<div class="products">
            <div id="ember1" class="product ember-view"><a href="/product/NameCompany" id="ember1" class="product-link ember-view">  <div class="product-card-header">
    <div id="ember1" class="product-card-logo ember-view"><img src="https://storage.googleapis.com/" id="ember1" class="product-avatar-img ember-view">
</div>
    <div class="product-card-header-t">
      <span class="product-card__name">NameCompany</span>
      <span class="product-card__tagline">Simple</span>
    </div>
  </div>

<!---->
    <div class="product-card-revenue">
      <div class="product-card-revenue-t">
        <span class="product-card-revenue-r">
          $0
          <span class="product-card-slash">/</span>
          <span class="product-card-period">month</span>
        </span>

        <span class="product-revenue">
<!---->          reported
        </span>
      </div>
    </div>
</div>

编辑:

如果我在xpath中使用extract_first()表示项目,则文件格式是正确的,但它只保存一个div中的信息,而忽略其余部分。

1 个答案:

答案 0 :(得分:0)

@Umair的回答是正确的

    def parse_attr(self, response):

       for items in response.xpath(''):
          item = TestItem()
          item['CompanyName'] = items.xpath('').extract()
          item['Revenue'] = items.xpath('').extract()
          item['Tag'] = items.xpath('').extract()
          yield item

我需要在循环内传递items(非项目),而不是响应对象。在所讨论的div范围内定义了响应。现在输出具有正确的格式。