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

如果有课的话,最好喝点汤。

  •  2
  • Kamikaze_goldfish  · 技术社区  · 7 年前

    有没有办法让BeautifulSoup寻找一个类,如果它存在,那么运行脚本?我正在尝试:

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

    我也试过了,但没用,因为属性太多而出错:

    if soup.has_attr("div", {"class": "info"})
        print("Tag Found")
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   nicholishen    7 年前

    你离得很近… soup.findall 如果找不到任何匹配项,将返回空列表。您的控制语句正在检查其返回的文本 bool 价值。相反,您需要通过省略 ==True

    if soup.find_all("div", {"class": "info"}):
        print("Tag Found")
    
        2
  •  2
  •   TapanHP    7 年前

    为什么不简单地说:

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