Beautifulsoup查找具有特定tex的HTML标记

2024-06-08 15:44:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我用beauthoulsoup和Python进行web抓取。在

例如,我有以下html文本

<body>
    <h5 class="h-bar">
        <b class="caret"></b>
        Model 11111
        Set Item
    </h5>
</body>

现在,我试图找到文本中包含单词“Set Item”的任何标记

我尝试了以下方法:

^{pr2}$

我希望得到这个:

    <h5 class="h-bar">
        <b class="caret"></b>
        Model 11111
        Set Item
    </h5>

但是,这将返回None。。我不知道为什么靓汤找不到匹配的。。 我该怎么做才能检测到文本中有“Set Item”的标记?在


Tags: 方法标记文本webmodelhtmlbarbody
1条回答
网友
1楼 · 发布于 2024-06-08 15:44:57

我也是个漂亮的新手。一定有更好的方法,但这个方法似乎有效:

from bs4 import BeautifulSoup
import re

def predicate(element):
    pattern = re.compile(r'Set Item')
    return element.name == u'h5' and element.find(text=pattern) 

if __name__ == '__main__':
    soup = BeautifulSoup(open('index.html').read())
    found = soup.find_all(predicate) # found: a list of elements
    print 'Found:', found

请原谅open().read()链。我只是在偷懒。在

输出:

^{pr2}$

更新

谓词不需要使用正则表达式:

def predicate(e):
    return e and e.name == u'h5' and 'Set Item' in e.text

相关问题 更多 >