【问题标题】:Beautifulsoup Finding HTML Tags with certain text [duplicate]Beautifulsoup 查找带有特定文本的 HTML 标签 [重复]
【发布时间】:2014-05-09 06:04:48
【问题描述】:

我正在使用 BeautifulSoup 和 Python 进行网页抓取。

例如,我有以下html文本

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

现在,我正在尝试查找文本中包含“Set Item”一词的任何标签。

我尝试了以下方法:

soup.find_all('h5', text="Set Item")

我希望得到这个:

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

但是,这返回 None.. 我不知道为什么美丽的汤找不到匹配的.. 我应该怎么做才能检测到文本中带有“设置项目”的标签?

【问题讨论】:

  • 因为h5 元素中有一个嵌套标签,您无法在text 上匹配。我认为这是对我之前回答的问题的欺骗。
  • 所以使用for h5 in soup.find_all('h5', text=False): if 'Set Item' in h5.text:,或者使用自定义函数进行搜索:soup.find_all(lambda t: t.name == 'h5' and 'Set Item' in t.text):
  • @MartijnPieters:你能链接到那个答案吗?这是谷歌搜索结果,我在搜索结果顶部附近看不到您的答案。如果它包含更完整的答案,那么能够从这里到达那里会很好
  • @BenKushigian:查看此帖中的重复横幅。
  • @MartijnPieters 哎呀,没看到第一名:D 谢谢

标签: python html regex web-scraping beautifulsoup


【解决方案1】:

我也是 BeautifulSoup 新手。一定有更好的方法,但这个方法似乎可行:

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() 链。我只是懒惰。

输出:

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

更新

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

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

【讨论】:

    猜你喜欢
    • 2010-10-26
    • 2016-01-10
    • 2018-10-11
    • 2016-01-10
    • 2020-10-05
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多