【问题标题】:Getting numbers from html tags [duplicate]从html标签获取数字[重复]
【发布时间】:2017-05-11 02:03:00
【问题描述】:

我正在尝试从此链接获取“span”标签中的 数字http://python-data.dr-chuck.net/comments_42.html

数据如下:

<tr><td>Modu</td><td><span class="comments">90</span></td></tr>
<tr><td>Kenzie</td><td><span class="comments">88</span></td></tr>
<tr><td>Hubert</td><td><span class="comments">87</span></td></tr>

代码如下:

import urllib
from BeautifulSoup import *

url = raw_input('Enter - ')
html = urllib.urlopen(url).read()

soup = BeautifulSoup(html)

# Retrieve all of the anchor tags
tags = soup('span')


numbers = [number.contents[0] for number in tags]
print numbers

当我打印numbers 时,它会显示如下内容:

[u'97', u'97', u'90', u'90', u'88', u'87', u'87', u'80', u'79', u'79', u'78', u'76', u'76', u'72', u'72', u'66', u'66', u'65', u'65', u'64', u'61', u'61', u'59', u'58', u'57', u'57', u'54', u'51', u'49', u'47', u'40', u'38', u'37', u'36', u'36', u'32', u'25', u'24', u'22', u'21', u'19', u'18', u'18', u'14', u'12', u'12', u'9', u'7', u'3', u'2']

为什么会得到那些你?我的目标是在没有 u 的情况下投射这些字符串并得到它们的总和。

【问题讨论】:

    标签: python python-2.7 beautifulsoup urllib


    【解决方案1】:

    您看到这一点是因为您正在打印列表。这会调用 Python repr() 方法,让您了解列表中的数据类型。

    u'' 表示您的列表包含 Unicode 字符串。您现在无需担心这一点(有关详细信息,请参阅 How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte")。

    由于您需要对值求和,您只需将 Unicode 字符串值转换为整数。

    您可以通过稍微修改您的代码来实现:

    numbers = [int(number.contents[0]) for number in tags]
    

    【讨论】:

      【解决方案2】:

      您的列表项是 unicode 类型,您可以将列表项转换为如下字符串:

      numbers = [str(number.contents[0]) for number in tags]
      

      要总结您的列表项,您需要将它们转换为整数,而不是字符串:

      numbers = [int(number.contents[0]) for number in tags]
      s = sum(numbers)
      

      输出:

      >>> my_list = [u'97', u'97', u'90', u'90', ...]
      >>>
      >>> [str(item) for item in my_list]
      ['97', '97', '90', '90', ...]
      >>> 
      >>> s = sum(int(item) for item in my_list)
      >>> s
      2553
      

      【讨论】:

      • 你不应该在没有传递编码类型的情况下对 Unicode (str()) 进行编码。如果任何字段包含非 ASCII,则用户将收到大量 UnicodeEncodeError 异常
      • @AlastairMcCormack 我同意你的看法,只是在这种情况下,我看到输入是数字而不是非 ascii 字符。
      猜你喜欢
      • 2018-12-23
      • 2023-03-10
      • 2018-05-07
      • 2015-04-25
      • 2019-03-31
      • 2012-01-19
      • 2011-07-31
      • 2018-02-24
      • 1970-01-01
      相关资源
      最近更新 更多