我正在使用 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
作为单个字符串?
我也想知道由此获得的输出。
你可以这样做:
breadcrum = [item.strip() for item in breadcrum if str(item)]
The if str(item)
将在删除新行字符后负责删除空列表项。
如果您想连接字符串,请执行以下操作:
','.join(breadcrum)
这会给你abc,def,ghi
EDIT
尽管上面给出了您想要的内容,正如线程中其他人指出的那样,但您使用 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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)