使用BeautifulSoup拉标签值

2024-06-07 04:39:55 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能告诉我如何使用BeautifulSoup提取标签的值吗?我读了文档,但很难浏览。例如,如果我有:

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

我怎么才能把那些忙着美化组/Python的“有趣的东西”拉出来呢?

编辑:我正在使用3.2.1版


Tags: text文档编辑title标签classspanfun
2条回答

子标签可通过.contents获得 http://www.crummy.com/software/BeautifulSoup/bs4/doc/#contents-and-children 在您的例子中,您可以发现标记使用其CSS类来提取内容

from bs4 import BeautifulSoup
soup=BeautifulSoup('<span title="Funstuff" class="thisClass">Fun Text</span>')
soup.select('.thisClass')[0].contents[0]

http://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors没有任何细节

你需要一些东西来识别你正在寻找的元素,很难分辨出这个问题是什么。

例如,这两个都会在美化组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']

相关问题 更多 >