使用Python中的beautifulsoup从网站中提取数字

Sal*_*sha 1 python regex beautifulsoup

我正在尝试使用urllib来获取一个html页面,然后使用beautifulsoup来提取数据.我想从comments_42.html获取所有数字并打印出它们的总和,然后显示数据的数量.这是我的代码,我正在尝试使用正则表达式,但它对我不起作用.

import urllib
from bs4 import BeautifulSoup
url = 'http://python-data.dr-chuck.net/comments_42.html'
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html,"html.parser")
tags = soup('span')
for tag in tags:
    print tag
Run Code Online (Sandbox Code Playgroud)

Lea*_*ner 7

使用BeautifulSoup的findAll()方法提取带有"注释"类的所有span标记,因为它们包含您需要的信息.然后,您可以根据需要对它们执行任何操作.

soup = BeautifulSoup(html,"html.parser")
data = soup.findAll("span", { "class":"comments" })
numbers = [d.text for d in data]
Run Code Online (Sandbox Code Playgroud)

这是输出:

[u'100', u'97', u'87', u'86', u'86', u'78', u'75', u'74', u'72', u'72',   u'72', u'70', u'70', u'66', u'66', u'65', u'65', u'63', u'61', u'60', u'60', u'59', u'59', u'57', u'56', u'54', u'52', u'52', u'51', u'47', u'47', u'41', u'41', u'41', u'38', u'35', u'32', u'31', u'24', u'19', u'19', u'18', u'17', u'16', u'13', u'8', u'7', u'1', u'1', u'1']
Run Code Online (Sandbox Code Playgroud)