【问题标题】:What type of output does soup.find() give in BeautifulSoup?在 BeautifulSoup 中,soup.find() 会给出什么类型的输出?
【发布时间】:2015-06-10 08:10:11
【问题描述】:

我正在查看 Taylor Swift 的歌曲 Blank Space 的链接。我试图隔离视图的数量。但我似乎无法将其用作数字。

这是它返回的内容:

Taylor Swift - Blank Space - YouTube
[u'721,891,621']

这不是一个真正的数字,因为如果我添加一个 1 会出现此错误:

print pizza[0].contents +1
TypeError: can only concatenate list (not "int") to list

这里是代码。

from bs4 import BeautifulSoup
import urllib2

url="https://www.youtube.com/watch?v=e-ORhEE9VVg"
page=urllib2.urlopen(url)
soup = BeautifulSoup(page.read())
print unicode(soup.title.string)


pizza= soup.find_all("div",{"class","watch-view-count"})
print pizza[0].contents

【问题讨论】:

  • 它在异常中说:can only concatenate list to list。因此pizza[0].contents 是一个列表。
  • 你在哪里使用soup.find()?您正在使用 soup.find_all() 然后访问结果的属性之一。 .content attribute documenation 告诉您它是什么类型:list 对象。

标签: python-2.7 beautifulsoup typeerror


【解决方案1】:

pizza[0].contents 是一个列表。它直接在您遇到的异常中说明。这可以通过检查type(pizza[0].contents)来验证

如果您尝试使用列表的第一个元素,请像为pizza 所做的那样使用索引器:pizza[0].contents[0]。你可以通过检查type(pizza[0].contents[0])来验证这个元素的类型

如果您需要一个整数,您可以在之后进行适当的转换。 There are several methods to convert your text to an integer when it has commas for thousands separators.

【讨论】:

  • 行:“print Pizza[0].contents[0]”返回以下错误:“TypeError: an integer is required” 行:我希望我能隔离字符串。然后我可以用你建议的方法把它变成一个整数。
  • 行:"type(pizza[0].contents[0])" 返回值 ""
  • @user2859603:这是一个 BeautifulSoup 类型。 So now you can refer to the documentation to convert it to a unicode string. 请注意有关在该类型上调用 unicode 的评论:unicode(pizza[0].contents[0])
  • 感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2020-12-24
  • 1970-01-01
  • 2014-01-21
  • 1970-01-01
  • 2019-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多