我试图解析一些文本sot帽子,我可以urlize (用标签包装)的链接,没有格式化。下面是一些示例文本:
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>'这是我离这里很远的地方
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>标记中的文本节点?
发布于 2015-10-03 19:09:53
Text节点保留它们的parent引用,因此您只需测试a标记:
for textNode in textNodes:
if textNode.parent and getattr(textNode.parent, 'name') == 'a':
continue # skip links
urlizedText = urlize(textNode)
textNode.replaceWith(urlizedText)https://stackoverflow.com/questions/32926395
复制相似问题