python - "Expected string or buffer"使用 Beautiful Soup 时出错

标签 python regex beautifulsoup

我正在尝试使用 Beautiful Soup 从 URL 中提取数字,然后对这些数字求和的代码,但我不断收到如下所示的错误:

Expected string or buffer

我认为这与正则表达式有关,但我无法确定问题所在。

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)

最佳答案

我推荐 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))

关于python - "Expected string or buffer"使用 Beautiful Soup 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33929317/

相关文章:

python - 如何使用 BeautifulSoup 匹配仅包含指定类而不包含任何其他类的标签?

python - 使用selenium在.click()之后获取新的html

python - 如果我有一个单词列表,如何有效地检查字符串是否不包含列表中的任何单词?

java - 正则表达式删除除关键字周围和引号之间的所有空格

python - 将文本区域输入转换为分段 HTML

ruby-on-rails - 为什么Ruby的正则表达式使用\A和\z而不是^和$?

python - 浏览零售商网站上的每件产品

python - 计算列表中连续的正值和负值

python - TensorFlow 'module' 对象没有属性 'global_variables_initializer'

python - Google oAuth2 python 应用程序无法在线打开登录页面