Python If else-如果找到具有bs4的值。。。其他的

Python If else-如果找到具有bs4的值。。。其他的,python,html,beautifulsoup,Python,Html,Beautifulsoup,我目前正在尝试混合使用HTML和Python。我的想法是: If I find a value in this HTML: Then run this method Else: Run this other method. 基本上我有 soup = soup(r.content, "lxml") findKey = soup.find('div', {'class': 'TalkingHand'})['data-key'] 到目前为止,我想做的是,如果我在HTML中找到一

我目前正在尝试混合使用HTML和Python。我的想法是:

If I find a value in this HTML:

   Then run this method

Else:

    Run this other method.
基本上我有

soup = soup(r.content, "lxml")
findKey = soup.find('div', {'class': 'TalkingHand'})['data-key']
到目前为止,我想做的是,如果我在HTML中找到一个任意值或这个元素,那么我应该在我的程序中做一个方法,我们可以称之为MethodFound,但是如果我们在HTML中找不到这个元素,那么我们应该做一些其他的事情:我们可以称之为DoNothing

我被if语句卡住了,我真的不知道从哪里开始

If(findKey == ..... <-- I dont know really)...

If(findKey==…您可以捕获当元素不存在时bs4将抛出的异常。下面是一个示例

try:
    soup = soup(r.content, "lxml")
    findKey = soup.find('div', {'class': 'TalkingHand'})['data-key']

    # Do stuff with the found key
except TypeError:
    # Key wasn't found do stuff
    pass

谢谢你的编辑:)谢谢!如果该项不存在,bs4将抛出异常,只需捕获它即可。没有必要,如果不是的话。我试过了,得到了expectipn
TypeError:“NoneType”对象不可下标
。例如,在这种情况下,我如何在If-else状态中编写这样的异常:D?@Well请检查我的答案。这正是我所需要的!非常感谢你!