【问题标题】:Pull Tag Value using BeautifulSoup使用 BeautifulSoup 拉取标签值
【发布时间】:2012-07-22 00:53:36
【问题描述】:

有人可以指导我如何使用 BeautifulSoup 提取标签的值吗?我阅读了文档,但很难浏览它。例如,如果我有:

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

我将如何在 BeautifulSoup/Python 中使用“Funstuff”?

编辑:我使用的是 3.2.1 版

【问题讨论】:

  • 这是 BeautifulSoup 3 还是 BeautifulSoup 4?

标签: python parsing tags beautifulsoup


【解决方案1】:

子标签可以通过 .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 拥有所需的所有细节

【讨论】:

    【解决方案2】:

    你需要有一些东西来识别你正在寻找的元素,而且在这个问题中很难说出它是什么。

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

    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 知道为什么吗?
    • 这只是 Python。如果您正在执行相对导入 (from BeautifulSoup import BeautifulSoup),请将行从 soup = BeautifulSoup.BeautifulSoup(... 更改为 soup = BeautifulSoup(... 请参阅 docs.python.org/tutorial/modules.html 了解更多信息。
    猜你喜欢
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    • 2018-12-12
    • 2016-04-01
    • 2018-04-23
    相关资源
    最近更新 更多