If-else - 如果找到bs4的值... Else

时间:2017-09-09 21:47:36

标签: 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中找到任何值或此元素,那么我应该在我的程序中执行一个方法,我们可以调用 MethodFound 但如果我们在HTML中找不到这个元素,那么我们应该做其他事情:我们可以称之为 DoNothing

我坚持在if语句中,我不知道从哪里开始。

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

1 个答案:

答案 0 :(得分:1)

您可以捕获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