2017-03-05 157 views
0

大家好,大家再一次在這裏蟒蛇noob。 我正在慢慢推進我的項目,但修復了一個錯誤,導致了另一個問題的到來。長話短說: 我檢查是否美麗soup.find_all值爲空

for tempNext in soup3.find_all(title=re.compile("^Next Page -")):

..loop,讓我找到一個href的值。如果價值存在,它會很好。如果不是,它會不斷重複使用之前的同一個。遺憾的是,這不像每次將值重置爲""那麼簡單,因爲這個for循環也在另一個循環內。

只是有想法,這是片斷的樣子:

soup3 = make_soup('http://www.automotiveforums.com/vbulletin/' + link) 
     while tempNumber < 4: 
      for postScrape in soup3.find_all(id=re.compile("^td_post_")): 
       post = "" 
       post += postScrape.get_text(strip=True) 
       postData += post + "\n" 
       print(post) 
      for tempNext in soup3.find_all(title=re.compile("^Next Page -")): 
       tempNextPage = "" 
       tempNextPage += (tempNext.get('href')) 
       print(tempNextPage) 
      soup3 = "" 
      soup3 = make_soup('http://www.automotiveforums.com/vbulletin/' + tempNextPage) 
      tempNumber += 1 
     tempNumber = 1 
    number += 1 
    print(number) 
    newUrl = "http://www.automotiveforums.com/vbulletin/" + nextPage 
    soup = make_soup(newUrl) 

所以我想知道是否有一種方法來檢查for tempNext in soup3.find_all(title=re.compile("^Next Page -")):值,如果它是空的,如果是,只要設置tempNextPage = ""然而,在過去的幾個小時裏,我無法弄清楚。

如果我在循環完成後將其設置爲空值,則不再刮取其他頁面。

感謝您花時間閱讀此問題,我們將不勝感激。

回答

1

聲明 - 或重置-tempNextPage變量在for循環之外,並且在for循環內將該變量重新分配給新值 - 而不是向其追加新值。這樣,如果soup3.find_all()沒有找到任何匹配的元素的tempNextPage值會留下空的,您可以根據tempNextPage是否爲空採取行動:

while tempNumber < 4: 
    tempNextPage = "" 
    for postScrape in soup3.find_all(id=re.compile("^td_post_")): 
     .... 
    for tempNext in soup3.find_all(title=re.compile("^Next Page -")): 
     tempNextPage = tempNext.get('href') 
     print(tempNextPage) 

    # process tempNextPage only if it is not empty 
    if not tempNextPage: 
     soup3 = make_soup('http://www.automotiveforums.com/vbulletin/' + tempNextPage) 
     .... 
    # do something else otherwise 
    else : 
     .... 
+0

尼斯之一,非常感謝在我的集羣期待。它實際上足以將它重置在FOR循環之外,但如果我添加了檢查(如果沒有),我會得到soup3.find_all的錯誤消息。然而,如果沒有它,它會正常工作,仍然會想出一種方法來避免它在一個大規模的嵌套循環中,但現在絕對是可行的。謝謝! – Norbis