【问题标题】:How to count the amount of prices pythonpython 如何计算价格的数量
【发布时间】:2015-11-19 15:26:13
【问题描述】:

我试图从我成功完成的网页中抓取一些价格

prices = item.find_all("span", {"class": "price"})
for price in prices:
    price_end = price.text.strip().replace(",","")[2:]
    print(price_end)

输出是:

13
36
50
65
12
52
60
85

因此,我总共有 8 个价格。我的问题是,如何使用 Python 自动计算输出中的价格?

我用 len 试过了,但它只是给了我相应数字的长度。

这似乎是直截了当的,但我总是撞墙。

你们能帮帮我吗?感谢您提供任何反馈。

【问题讨论】:

    标签: python python-3.x web-crawler output


    【解决方案1】:
    count = 0
    prices = item.find_all("span", {"class": "price"})
    for price in prices:
        price_end = price.text.strip().replace(",","")[2:]
        count += 1
        print(price_end)
    print(count, " prices found")
    

    【讨论】:

    • 您好,感谢您的反馈。不会导致预期的结果。我得到以下结果: 1 个价格找到 1 个价格找到 1 个价格找到 1 个价格找到 它没有总结价格的数量。有什么建议吗?:)
    • 检查缩进。 print 应该在循环之外。
    • 它在循环之外,但似乎不起作用。 len(prices) 也不好用
    • 是否有没有显示的外循环?看起来打印在某个循环中,因为您得到的不止一个。
    • 抱歉,我忘了提到一个外部循环。现在可以了。感谢您的反馈和耐心:)
    【解决方案2】:

    您可以将它们列在一个列表中:

    price_list=[]
    prices = item.find_all("span", {"class": "price"})
    for price in prices:
        price_end = price.text.strip().replace(",","")[2:]
        price_list.append(price_end)
    
    print(len(price_list))
    print('\n'.join(price_list))
    

    (如果每个条目都有一个价格,len(prices) 也可以工作......)

    【讨论】:

    • 感谢您的反馈
    【解决方案3】:

    您可能希望将价格存储在列表中。这是使用 for 循环的另一种方法。这称为列表推导:

    prices = [
        price.text.strip().replace(",","")[2:]
        for price in item.find_all("span", {"class": "price"})
    ]
    

    这会列出价格。然后,您可以打印价格数量和每个价格(此处使用字符串格式):

    print("{price_count} prices: {prices}".format(
        price_count=len(price_list)),
        prices=prices,
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      相关资源
      最近更新 更多