Flow Control,If语句循环,else语句不执行

时间:2017-01-14 23:02:39

标签: python if-statement for-loop while-loop flow-control

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

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子句。

1 个答案:

答案 0 :(得分:2)

你需要:

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

您的旧语法:

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

相当于:

item

这是Python's chaining behaviour