我正在尝试解析一些文本,以便我可以对未格式化的链接进行 URL 化(用标签包装)。以下是一些示例文本:
text = '<p>This is a <a href="https://google.com">link</a>, this is also a link where the text is the same as the link: <a href="https://google.com">https://google.com</a>, and this is a link too but not formatted: https://google.com</p>'
这是我迄今为止从 here 得到的内容:
from django.utils.html import urlize
from bs4 import BeautifulSoup
...
def urlize_html(text):
soup = BeautifulSoup(text, "html.parser")
textNodes = soup.findAll(text=True)
for textNode in textNodes:
urlizedText = urlize(textNode)
textNode.replaceWith(urlizedText)
return = str(soup)
但这也会捕获示例中的中间链接,导致其双重包裹在 <a>
中标签。结果是这样的:
<p>This is a <a href="https://djangosnippets.org/snippets/2072/" target="_blank">link</a>, this is also a link where the test is the same as the link: <a href="https://djangosnippets.org/snippets/2072/" target="_blank"><a href="https://djangosnippets.org/snippets/2072/">https://djangosnippets.org/snippets/2072/</a></a>, and this is a link too but not formatted: <a href="https://djangosnippets.org/snippets/2072/">https://djangosnippets.org/snippets/2072/</a></p>
我可以对 textNodes = soup.findAll(text=True)
做什么?这样它只包含尚未包含在 <a>
中的文本节点标签?
最佳答案
文本节点保留其parent
引用,因此您可以只测试a
标签:
for textNode in textNodes:
if textNode.parent and getattr(textNode.parent, 'name') == 'a':
continue # skip links
urlizedText = urlize(textNode)
textNode.replaceWith(urlizedText)
关于python - 使用 Python 和 BeautifulSoup,仅选择未包含在 <a> 中的文本节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32926395/