python - 使用 Python 和 BeautifulSoup,仅选择未包含在 <a> 中的文本节点

标签 python beautifulsoup

我正在尝试解析一些文本,以便我可以对未格式化的链接进行 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">&lt;a href="https://djangosnippets.org/snippets/2072/"&gt;https://djangosnippets.org/snippets/2072/&lt;/a&gt;</a>, and this is a link too but not formatted: &lt;a href="https://djangosnippets.org/snippets/2072/"&gt;https://djangosnippets.org/snippets/2072/&lt;/a&gt;</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/

相关文章:

python - BeautifulSoup 编码错误中文字符

python - 识别重复项并选择要删除的重复行

python - pyspark 根据两列中的数据创建字典

python - 用 BeautifulSoup 抓取不同的元素 : avoid duplicating in nested elements

python - 如何在 Beautifulsoup 中分解 HTML 元素以将它们插入到 MySQL 数据库表中?

python - 从下拉列表中抓取值

python - 在 Python 中,为什么一个负数的偶次幂仍然是负数?

python - 从 Python 打开 Excel 应用程序

c++ - 使用 python 正则表达式从 C++ 源中提取命名空间

python - 即使某些元素不存在,也要刮掉所有内容