【问题标题】:Removing Tags from HTML Parsed with BeautifulSoup从使用 BeautifulSoup 解析的 HTML 中删除标签
【发布时间】:2011-04-04 21:13:25
【问题描述】:

我是 python 新手,我正在使用 BeautifulSoup 解析网站然后提取数据。我有以下代码:

for line in raw_data: #raw_data is the parsed html separated into smaller blocks
    d = {}
    d['name'] = line.find('div', {'class':'torrentname'}).find('a')
    print d['name']

<a href="/ubuntu-9-10-desktop-i386-t3144211.html">
<strong class="red">Ubuntu</strong> 9.10 desktop (i386)</a>

通常我可以通过以下方式提取“Ubuntu 9.10 desktop (i386)”:

d['name'] = line.find('div', {'class':'torrentname'}).find('a').string

但由于强大的 html 标签,它返回 None。有没有办法提取强标签然后使用 .string 或者有更好的方法吗?我曾尝试使用 BeautifulSoup 的 extract() 函数,但无法正常工作。

编辑:我刚刚意识到,如果有两组强标签,我的解决方案将不起作用,因为单词之间的空格被遗漏了。有什么办法可以解决这个问题?

【问题讨论】:

标签: python html parsing beautifulsoup


【解决方案1】:

使用“.text”属性:

d['name'] = line.find('div', {'class':'torrentname'}).find('a').text

或者在 findAll(text=True) 上做一个连接:

anchor = line.find('div', {'class':'torrentname'}).find('a')
d['name'] = ''.join(anchor.findAll(text=True))

【讨论】:

  • 这不起作用。它不会在如下示例中保留空格:Ubuntu Linux。它以 UbuntuLinux 的形式出现。
  • 非常感谢,效果很好!你能解释一下第二行代码是如何工作的吗?
  • BeautifulSoup 文档说 text 参数允许您“搜索 NavigableString 对象而不是标签”。 findAll 返回一个 python 列表,然后可以将其连接在一起 (.join) 以形成一个字符串。 crummy.com/software/BeautifulSoup/documentation.html
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
  • 1970-01-01
相关资源
最近更新 更多