【问题标题】:Beautiful Soup - identify tag based on position next to commentBeautiful Soup - 根据评论旁边的位置识别标签
【发布时间】:2011-07-11 08:55:00
【问题描述】:

我正在使用美丽的汤。

有什么方法可以让我根据评论旁边的位置(解析树中未包含的内容)获取标签?

例如,假设我有...

<html>
<body>
<p>paragraph 1</p>
<p>paragraph 2</p>
<!--text-->
<p>paragraph 3</p>
</body>
</html>

在这个例子中,如果我正在搜索评论“&lt;!--text--&gt;”,我如何识别&lt;p&gt;paragraph 2&lt;/p&gt;

感谢您的帮助。

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    评论出现在 BeautifulSoup 解析树中,就像任何其他节点一样。例如,要查找带有文本 some comment text 的评论,然后打印出之前的 &lt;p&gt; 元素,您可以这样做:

    from BeautifulSoup import BeautifulSoup, Comment
    
    soup = BeautifulSoup('''<html>
    <body>
    <p>paragraph 1</p>
    <p>paragraph 2</p>
    <!--some comment text-->
    <p>paragraph 3</p>
    </body>
    </html>''')
    
    def right_comment(e):
        return isinstance(e, Comment) and e == 'some comment text'
    
    e = soup.find(text=right_comment)
    
    print e.findPreviousSibling('p')
    

    ...这将打印出来:

    <p>paragraph 2</p>
    

    【讨论】:

    • 非常感谢马克。太好了。
    猜你喜欢
    • 2018-04-26
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    相关资源
    最近更新 更多