【问题标题】:Scrapy - python - web crawler. Output list of all xpaths instead of only first matchScrapy - python - 网络爬虫。所有 xpath 的输出列表,而不仅仅是第一个匹配项
【发布时间】:2015-09-04 21:49:50
【问题描述】:
revenues_in = MapCompose(MatchEndDate(float)) 

revenues_out = Compose(imd_filter_member, imd_mult, imd_max)


def add_xpath(self, field_name, xpath, *processors, **kw):

    values = self._get_values(xpath, **kw)

    self.add_value(field_name, values, *processors, **kw)

    return len(self._values[field_name])


def add_xpaths(self, name, paths):

    for path in paths:

        match_count = self.add_xpath(name, path)

        if match_count > 0:

            return match_count

    return 0



self.add_xpaths('revenues', [

        '//us-gaap:Revenues',

        '//us-gaap:SalesRevenueNet',

        '//us-gaap:SalesRevenueGoodsNet',

        '//us-gaap:SalesRevenueServicesNet',

        '//us-gaap:RealEstateRevenueNet',

        '//*[local-name()="NetRevenuesIncludingNetInterestIncome"]',

        '//*[contains(local-name(), "TotalRevenues") and contains(local-name(), "After")]',

        '//*[contains(local-name(), "TotalRevenues")]',

        '//*[local-name()="InterestAndDividendIncomeOperating" or local-name()="NoninterestIncome"]',

        '//*[contains(local-name(), "Revenue")]'

    ])

目前,代码只输出 xpath 列表中的第一个匹配项。我希望它返回所有匹配的 xpath 中的最大值。请指教。

这当然是我认为相关的代码的一小部分。如果您想查看任何其他代码,请访问https://github.com/eliangcs/pystock-crawler/tree/master/pystock_crawler

感谢您的宝贵时间和帮助!

【问题讨论】:

    标签: python xpath web web-crawler scrapy


    【解决方案1】:

    这不起作用,因为 add_xpaths 函数在每次循环结束时返回一个值。这会导致循环在第一次运行后退出。相反,您需要将计数存储在一个变量中,并在您遍历整个数据结构时返回它。

    而不是这个:

    def add_xpaths(self, name, paths):
        for path in paths:
            match_count = self.add_xpath(name, path)
             if match_count > 0:
                 return match_count
        return 0
    

    试试这个:

    def add_xpaths(self, name, paths):
        match_count = 0
        for path in paths:
            match_count += self.add_xpath(name, path)
        return match_count
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-12
      • 1970-01-01
      • 2014-04-24
      • 1970-01-01
      相关资源
      最近更新 更多