从Python BeautifulSoup的输出中删除换行符'\n'

11

我正在使用 Python Beautiful Soup 来获取以下内容:

<div class="path">
    <a href="#"> abc</a>
    <a href="#"> def</a>
    <a href="#"> ghi</a>
</div>

我的代码如下:

html_doc="""<div class="path">
    <a href="#"> abc</a>
    <a href="#"> def</a>
    <a href="#"> ghi</a>
</div>"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc)

path = soup.find('div',attrs={'class':'path'})
breadcrum = path.findAll(text=True)

print breadcrum

输出结果如下:

[u'\n', u'abc', u'\n', u'def', u'\n', u'ghi',u'\n']

如何仅以单个字符串形式获得此形式的结果:abc,def,ghi

另外,我想了解所获得输出的相关信息。

3个回答

11

你可以这样做:

breadcrum = [item.strip() for item in breadcrum if str(item)]

如果列表中有空项,if str(item) 可以去除这些空项及换行符。

如果你想连接字符串,可以使用以下代码:

','.join(breadcrum)

这将为您提供abc,def,ghi

编辑

虽然上面的方法可以得到您想要的内容,但正如帖子中其他人指出的那样,您使用BS提取锚文本的方式不正确。一旦您拥有了感兴趣的div,您应该使用它来获取其子元素,然后获取锚文本。就像这样:

path = soup.find('div',attrs={'class':'path'})
anchors = path.find_all('a')
data = []
for ele in anchors:
    data.append(ele.text)

然后执行','.join(data)


item.rstrip('\n') 更明确地表达了操作的意图。 - Burhan Khalid
现在的输出是:u'abc,,def,,ghi,'? - Anish
1
如果div中还有其他文本,则这将失败,显然打败了使用BS的目的。 - thefourtheye
@thefourtheye同意了,已经更新答案以反映这一点。 - shaktimaan
@shaktimaan,我有一个更好的版本,与你的回答非常相似 :) 既然你的回答已被接受,那我就删除我的回答。 - thefourtheye
我不明白。这不可以通过简单的列表推导完成吗?为什么需要将其附加到新列表中? - WGS

7
如果您只是在面包屑导航中删除项目,您最终会得到一个空项目列表。您可以按照shaktimaan的建议进行操作,然后使用。
breadcrum = filter(None, breadcrum)

或者您可以事先从html_doc中删除它们:
mystring = mystring.replace('\n', ' ').replace('\r', '')

无论哪种方式获取您的字符串输出,都可以像这样操作:
','.join(breadcrum)

2
除非我漏掉了什么,只需将strip和列表推导结合起来即可。 代码:
from bs4 import BeautifulSoup as bsoup

ofile = open("test.html", "r")
soup = bsoup(ofile)

res = ",".join([a.get_text().strip() for a in soup.find("div", class_="path").find_all("a")])
print res

结果:

abc,def,ghi
[Finished in 0.2s]

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