使用BeautifulSoup提取标签值

6

请问如何使用BeautifulSoup获取标签的值?我阅读了文档,但很难找到具体方法。例如,如果有以下代码:

<span title="Funstuff" class="thisClass">Fun Text</span>

我该如何使用BeautifulSoup/Python仅提取“ Funstuff”?
编辑:我正在使用版本3.2.1

这是BeautifulSoup 3还是BeautifulSoup 4? - Steven Huwig
2个回答

7

在这个问题中,你需要有一些东西来识别你要查找的元素,很难确定它是什么。

例如,在BeautifulSoup 3中,这两个示例都将打印出“Funstuff”。一个查找span元素并获取标题,另一个查找具有给定类的spans。还有许多其他有效的方法可以达到这个目的。

import BeautifulSoup
soup = BeautifulSoup.BeautifulSoup('<html><body><span title="Funstuff" class="thisClass">Fun Text</span></body></html>')
print soup.html.body.span['title']
print soup.find('span', {"class": "thisClass"})['title']

问题:我的BeautifulSoup导入语句是: from BeautifulSoup import BeautifulSoup, CData然而,上述代码似乎只有在我这样做时才能正常工作: import BeautifulSoup有什么想法吗? - user1463925
这只是Python而已。如果你正在进行相对导入(from BeautifulSoup import BeautifulSoup),那么将该行从soup = BeautifulSoup.BeautifulSoup(...更改为soup = BeautifulSoup(...。有关更多信息,请参见http://docs.python.org/tutorial/modules.html。 - Steven Huwig

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接