来自这个 html 源:
<div class="category_link">
Category:
<a href="/category/personal">Personal</a>
</div>
我想提取文本 Category:
这是我使用 Python/BeautifulSoup 的尝试(输出作为注释 - 在 # 之后)
parsed = BeautifulSoup(sample_html)
parsed_div = parsed.findAll('div')[0]
parsed_div.firstText() # <a href="/category/personal">Personal</a>
parsed_div.first() # <a href="/category/personal">Personal</a>
parsed_div.findAll()[0] # <a href="/category/personal">Personal</a>
我希望“文本节点”作为第一个子节点可用。关于如何解决这个问题有什么建议吗?
最佳答案
我相当确定以下内容应该可以满足您的需求
parsed.find('a').previousSibling # or something like that
这将返回一个几乎相同的 NavigableString
实例
作为 unicode
实例的东西,但你可以调用 unicode
来获得
unicode 对象。
我会看看是否可以对此进行测试,然后让您知道。
编辑:我刚刚确认它有效:
>>> from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup('<div class=a>Category: <a href="/">a link</a></div>')
>>> soup.find('a')
<a href="/">a link</a>
>>> soup.find('a').previousSibling
u'Category: '
>>>
关于python - 使用 BeautifulSoup 在第一个子标签之前提取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10154289/