2015-11-26 86 views
1

我试图将使用美丽的汤拉号从一个URL,然后总结这些数字的代码,但我不断收到类似如下的错误:“预期的字符串或缓冲区”使用错误美丽的汤

预期的字符串或缓冲区

我认为这是关系到正则表达式,但我不能查明问题。

import re 
import urllib 

from BeautifulSoup import * 
htm1 = urllib.urlopen('https://pr4e.dr-chuck.com/tsugi/mod/python-data/data/comments_42.html').read() 
soup = BeautifulSoup(htm1) 
tags = soup('span') 

for tag in tags: 
    y = re.findall ('([0-9]+)',tag.txt) 

print sum(y) 

回答

1

我建议bs4代替BeautifulSoup(这是旧版本)。您还需要改变这一行:

y = re.findall ('([0-9]+)',tag) 

是这样的:

y = re.findall ('([0-9]+)',tag.text) 

看看这进一步让你:

sum = 0 #initialize the sum 
for tag in tags: 
    y = re.findall ('([0-9]+)',tag.text) #get the text from the tag                                  
    print(y[0]) #y is a list, print the first element of the list                                  
    sum += int(y[0]) #convert it to an integer and add it to the sum                                 

print('the sum is: {}'.format(sum)) 
+0

你说的没错,当我改变了行根据你的建议,我已经通过了错误,但代码仍然无法按预期工作。我上周尝试安装bs4,但无法正确安装,因此我决定坚持使用bs3。 –

+0

请将上面的代码更新到您当前的版本 - 我的测试看起来像你很近。 – davejagoda

+0

当前版本是什么意思?我使用的是Python 2.7和bs3 –

相关问题