【问题标题】:Edit content in BeautifulSoup ResultSet在 BeautifulSoup ResultSet 中编辑内容
【发布时间】:2013-05-29 15:07:38
【问题描述】:

我的最终目标是把 BeautifulSoup ResultSet 中的数字加起来:

[<span class="u">1,677</span>, <span class="u">114</span>, <span class="u">15</span>]

<class 'BeautifulSoup.ResultSet'>

因此,最终得到: 总和 = 1806

但似乎迭代列表的常用技术在这里不起作用。 最后我知道我必须提取数字,删除逗号,然后将它们相加。但我有点卡住了,尤其是在提取数字方面。

非常感谢一些帮助。谢谢

【问题讨论】:

    标签: python parsing web-scraping beautifulsoup


    【解决方案1】:

    似乎常用的迭代技术对我有用。这是我的代码:

    from bs4 import BeautifulSoup
    # or `from BeautifulSoup import BeautifulSoup` if you are using BeautifulSoup 3
    
    text = "<html><head><title>Test</title></head><body><span>1</span><span>2</span></body></html>"
    soup = BeautifulSoup(text)
    spans = soup.findAll('span')
    total = sum(int(span.string) for span in spans)
    print(total)
    # 3
    

    你试过什么?您有任何我们可以处理的错误消息吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-09
      • 1970-01-01
      • 2013-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-06
      相关资源
      最近更新 更多