【问题标题】:Python Beautiful Soup - How to detect that two Tag or NavigableString objects are the same in the DOMPython Beautiful Soup - 如何检测 DOM 中的两个 Tag 或 NavigableString 对象是否相同
【发布时间】:2018-03-21 21:40:10
【问题描述】:

如何使用 Beautiful Soup API 检查从同一个 BeautifulSoup 对象检索到的两个 Tag 或 NavigableString 对象是否真的是 DOM 中的同一个对象?

例如,下面最后一行代码的计算结果为 True,但我需要能够检测到 first_paragraphsecond_paragraph 在 DOM 中不是同一个对象。

from bs4 import BeautifulSoup

example_html_str = """\
    <html>
    <head></head>
    <body>
        <p>Content</p>
        <p>Content</p>
    </body>
    </html>
    """

soup = BeautifulSoup(example_html_str, "lxml")
paragraphs = soup.find_all("p")

first_paragraph = paragraphs[0] #First paragraph
second_paragraph = paragraphs[1] #Second paragraph

# The below evaluates to true, but they are not
# from the same part of the DOM.
print(first_paragraph == second_paragraph)

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    假设汤对象始终是一个对象(而不是通过不同汤对象处理的同一个 HTML 文档),您应该可以这样做:

    soup = BeautifulSoup(example_html_str, "lxml")
    first_paragraph = soup.find_all("p")[0]
    second_paragraph = soup.find_all("p")[1]
    another_paragraph = soup.find_all("p")[0]
    first_paragraph is second_paragraph
    # is False
    first_paragraph is another_paragraph
    # is True
    

    【讨论】:

    • 已解决,谢谢!检查对象是否相同是有意义的。
    • 如果答案正确,请将其标记为已接受答案(在计票下查看)。
    猜你喜欢
    • 2018-11-15
    • 2021-01-16
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 2012-06-23
    • 2016-04-16
    • 1970-01-01
    相关资源
    最近更新 更多