Beautifulsoup,如果类存在

时间:2018-08-20 23:56:20

标签: python if-statement beautifulsoup

有没有一种方法可以使BeautifulSoup查找一个类,如果存在,请运行该脚本?我正在尝试:

if soup.find_all("div", {"class": "info"}) == True:
    print("Tag Found")

我也尝试过,但是没有用,并给出了关于属性过多的错误:

if soup.has_attr("div", {"class": "info"})
    print("Tag Found")

2 个答案:

答案 0 :(得分:2)

为什么不简单地这样:

if soup.find("div", {"class": "info"}) is not None:
    print("Tag Found")

答案 1 :(得分:1)

您非常接近...如果找不到任何匹配项,soup.findall将返回一个空列表。您的控制语句正在检查其返回值是否为文字bool。相反,您需要通过省略==True

来检查其真实性。
if soup.find_all("div", {"class": "info"}):
    print("Tag Found")