我用的是美汤。有这样一个标签:
<li><a href="example"> s.r.o., <small>small</small></a></li>
我想获取 anchor 内的文本 <a>
只有标签,没有来自 <small>
的任何标签输出中的标签;即“ s.r.o.,
”
我试过了 find('li').text[0]
但它不起作用。
BS4中有没有可以做到这一点的命令?
最佳答案
一个选择是从 contents
中获取第一个元素a
元素的:
>>> from bs4 import BeautifulSoup
>>> data = '<li><a href="example"> s.r.o., <small>small</small></a></li>'
>>> soup = BeautifulSoup(data)
>>> print soup.find('a').contents[0]
s.r.o.,
另一种方法是找到 small
标签并获得 previous sibling :
>>> print soup.find('small').previous_sibling
s.r.o.,
好吧,还有各种替代/疯狂的选择:
>>> print next(soup.find('a').descendants)
s.r.o.,
>>> print next(iter(soup.find('a')))
s.r.o.,
关于python - BS4 : Getting text in tag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25251841/