如何在BeautifulSoup

时间:2017-04-11 15:47:34

标签: beautifulsoup

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



<tr flag='t'><td flag='f'></td></tr>
&#13;
&#13;
&#13;

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

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

然后我得到像

这样的错误
KeyError: 'myrule'

任何人都可以帮助我,为什么它不起作用。

感谢。

1 个答案:

答案 0 :(得分: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>]