从 html 个标签获取数字

Getting numbers from html tags

我正在尝试从这个 link 的 "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']

为什么要得到那些你的?我的 objective 是转换那些不带 u 的字符串并得到它们的总和。

您的列表项是 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

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

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

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

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

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