首页 文章

从使用BeautifulSoup解析的HTML中删除标签

提问于
浏览
3

我是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桌面(i386)':

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

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

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

1 回答

  • 3

    使用“.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))
    

相关问题