流程控制,If 语句循环,else 语句不执行

Flow Control, If statement looping, else statement not executing

在以下代码中,我无法通过第一个 if 语句并继续执行其他 statement,即使我故意将其设置为 false:

while not scraped:
    print("sleep....")
    time.sleep(1)
    try:
        res = requests.get(url).content
        soup = BeautifulSoup(res, 'lxml')
        links = soup.find_all("span", {"id":"reasonabledoubt"})
        dip = soup.find_all("div")
        print("searching divs")
        if 'keyword' in str(dip) == True:
            print(url)
            print("LINK SCRAPED")
            print(url + " link scraped")
            scraped = True
        else:
            for word in links:
                 print("testing for loop")
                 #rest of code

所以基本上如果在 str(dip) 中找不到关键字,我需要执行 else 子句。

你需要:

if 'keyword' in str(dip):

您的旧语法:

if 'keyword' in str(dip) == True:

相当于:

if 'keyword' in str(dip) and str(dip) == True

这是Python's chaining behaviour