代码之家  ›  专栏  ›  技术社区  ›  Chan

如何在beauthulsoup中查找给定文本的标记名

  •  0
  • Chan  · 技术社区  · 6 年前

    我有以下html代码:

    soup = BeautifulSoup("<div class='mydiv'><p style='xyz'>123</p><p>456</p><p style='xyz'>789</p><p>abc</p></div>", 'lxml')
    

    现在,我有一个文本“456”。

    我想在所有的标签中找到文本,这些标签都有相同的标签名,包含文本‘456’。

    也就是说,在html中, <p>456</p> 包含 456 ,那么我们应该找到 abc <p>abc</p> 但不是 123 和 789 因为 <p style> 在里面 <p style='xyz'>123</p> <p style='xyz'>789</p>

    请注意 <p> 上面可以是其他标记,例如 <div> .

    soup.find('p') 应该避免。

    最终结果是 [456, 789] .

    有点复杂。

    我们如何解决这个问题?

    谢谢。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Andrej Kesely    6 年前

    此脚本将打印共享标记名的所有标记和包含字符串“456”的标记属性:

    txt = '''
        <div class='mydiv'>
            <p style='xyz'>123</p>
            <p>456</p>
            <p style='xyz'>789</p>
            <p>abc</p>
        </div>'''
    
    text_to_find = '456'
    soup = BeautifulSoup(txt, 'html.parser')
    
    tmp = soup.find(lambda t: t.contents and t.contents[0] == text_to_find)
    if tmp:
        for tag in soup.find_all(lambda t: t.name == tmp.name and t.attrs == tmp.attrs):
            print(tag)
    

    印刷品:

    <p>456</p>
    <p>abc</p>
    

    对于输入“123”:

    <p style="xyz">123</p>
    <p style="xyz">789</p>
    
        2
  •  0
  •   DJSchaffner    6 年前

    from bs4 import BeautifulSoup
    
    soup = BeautifulSoup("<div class='mydiv'><p style='xyz'>123</p><p>456</p><p style='xyz'>789</p><p>abc</p></div>", 'lxml')
    
    # Find all tags first and then look for the one matching your string
    found = [x for x in soup.findAll() if x.text == "456"]
    
    for p in found:
      print(p)
    
    # Using findAll functionality directly
    found = soup.findAll(text="456")
    
    for p in found:
      print(p)
    

    <p>456</p>

    但是请注意,使用您收到的第二种方法 NavigableString 对象与否 Tag 物体!

        3
  •  0
  •   UWTD TV    6 年前

    soup = BeautifulSoup("<div class='mydiv'><p style='xyz'>123</p><p>456</p><p style='xyz'>789</p><p>abc</p></div>", 'html5lib')
    
    tags = soup.find_all()
    for tag in tags:
        if tag.get('style'):
            tag.extract()
    
    for tag in soup.select('html body'):
        print(tag.get_text('\n'))
    

    印刷品:

    456
    abc