【问题标题】:How can i use a function in find_all() in BeautifulSoup我如何在 BeautifulSoup 的 find_all() 中使用函数
【发布时间】:2017-04-11 15:47:34
【问题描述】:

我在我的项目中使用 bs4。现在我得到类似的东西:

<tr flag='t'><td flag='f'></td></tr>

我已经知道我可以在 find_all() 中使用函数。所以我用

def myrule(tag):
    return tag['flag']=='f' and tag.parent['flag']=='t'; 
soup.find_all(myrule)

然后我得到类似的错误

KeyError: 'myrule'

谁能帮我解决这个问题,为什么它不起作用。

谢谢。

【问题讨论】:

    标签: beautifulsoup


    【解决方案1】:

    您正在汤对象中搜索每个可能的标签以查找名为flag 的属性。如果当前传递的标签没有那个属性,它会抛出一个错误,程序会停止。

    在检查其余部分之前,您应该首先验证标签是否具有该属性。像这样:

    from bs4 import BeautifulSoup
    
    example = """<tr flag='t'><td flag='f'></td></tr>"""
    
    soup = BeautifulSoup(example, "lxml")
    
    def myrule(tag):
      return "flag" in tag.attrs and tag['flag']=='f' and tag.parent['flag']=='t'; 
    
    print(soup.find_all(myrule))
    

    输出:

    [<td flag="f"></td>]
    

    【讨论】:

      猜你喜欢
      • 2020-01-24
      • 2021-11-25
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      • 2021-06-29
      • 2021-02-23
      • 2021-07-06
      相关资源
      最近更新 更多