我试图从HTML数据中提取数字,以便得到它们的总和。但是,当我试图运行它时,我遇到了上述错误。它指的是"data =“行。在这一行代码中,这个错误指的是什么?我是否正确地设置了"for“循环?谢谢你的想法。
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')
data = soup.findall("span", {"Comments":"Comments"})
numbers = [d.text for d in data]
summation = 0
for tag in tags:
print tags
y= tag.finall("span").text
summation = summation + int(y)
print summation--这就是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>发布于 2015-12-21 04:21:50
首先,在findall()中没有BeautifulSoup方法--有find_all()。此外,您基本上是在搜索具有Comments属性的具有Comments值的元素:
soup.findall("span", {"Comments":"Comments"}) 而且,这是Python,您可以更容易地用一个sum()来总结。
固定版本:
data = soup.find_all("span", {"class": "comments"})
print sum(int(d.text) for d in data) # prints 2482https://stackoverflow.com/questions/34388900
复制相似问题