【问题标题】:How to search text excluding html tags but return the corresponding html如何搜索不包括html标签的文本但返回相应的html
【发布时间】:2022-01-10 11:30:18
【问题描述】:

我有一些网页,我熟悉其中的一些内容,但并不真正了解网页本身的结构,因此网页可以采用以下形式
第 1 页

<strong> Some text</strong> I'm interested in <p> searching </p>

第 2 页

<b> Some text I'm interested in </b> searching

第 3 页

<div><p> Some text I'm interested in searching and this is some other text</p></div>

是否有可能在不编写棘手的正则表达式的情况下搜索页面并查找子字符串,然后也获得封闭的 html? 现在我只是提取文本并使用子字符串进行搜索,但我还想返回 html。有没有办法使用Beautifulsoup 来实现这一点?

html = urllib.request.urlopen('path').read().decode('utf-8')
soup = BeautifulSoup(html, 'html.parser')
text = soup.get_text()
result = re.search(text, "Some text I'm interested in searching", re.I)

所以第1页的输出,我可以提取(如上图)

<strong> Some text</strong> I'm interested in <p> searching </p>

等等..

【问题讨论】:

    标签: python regex beautifulsoup


    【解决方案1】:

    您可以尝试使用regexbeautifulsoup 进行搜索:

    import bs4
    import re
    
    html = """<strong> Some text</strong> I'm interested in <p> searching </p>
    <b> Some text I'm interested in </b> searching
    <div><p> Some text I'm interested in searching and this is some other text</p></div>"""
    
    soup = bs4.BeautifulSoup(html)
    soup.find(text=re.compile("Some text I'm interested in searching")).parent
    

    输出

    <p> Some text I'm interested in searching and this is some other text</p>
    

    【讨论】:

    • 嗨,我已经对问题进行了编辑,基本上这些是不同的页面。我想提取所有这三种情况。
    猜你喜欢
    • 2011-04-09
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-16
    • 2015-08-12
    相关资源
    最近更新 更多