我想從這個鏈接得到號在「間距」標籤:http://python-data.dr-chuck.net/comments_42.html從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']
爲什麼它得到那些你的?我的目標是拋棄那些沒有你的字符串並獲得它們的總和。
你不應該不經過編碼類型編碼爲Unicode('STR()')。如果任何字段包含非ASCII,那麼用戶將得到一個巨大的UnicodeEncodeError異常 –
@AlastairMcCormack我同意你的看法,就在這種情況下,我發現輸入的數字不是非ascii字符。 – ettanany