Python 检查beautiful soup.find_all值是否为空
大家好,这里是python noob。 我的项目进展缓慢,但修复了一个bug,导致了另一个问题。长话短说: 我有 对于soup3中的tempNext.find_alltitle=re.compile^下一页-: …循环,让我找到href值。如果该值存在的话,它工作得很好。如果没有,它将继续重复使用以前的同一个。遗憾的是,这并不像每次重置值那么简单,因为这个for循环也在另一个循环中 为了了解这一点,以下是代码片段的外观:Python 检查beautiful soup.find_all值是否为空,python,loops,web-scraping,null,beautifulsoup,Python,Loops,Web Scraping,Null,Beautifulsoup,大家好,这里是python noob。 我的项目进展缓慢,但修复了一个bug,导致了另一个问题。长话短说: 我有 对于soup3中的tempNext.find_alltitle=re.compile^下一页-: …循环,让我找到href值。如果该值存在的话,它工作得很好。如果没有,它将继续重复使用以前的同一个。遗憾的是,这并不像每次重置值那么简单,因为这个for循环也在另一个循环中 为了了解这一点,以下是代码片段的外观: soup3 = make_soup('http://www.automot
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)
所以我想知道是否有一种方法可以检查soup3中的tempNext。find_alltitle=re.compile^Next Page-:value如果为空,如果为空,只需设置tempNextPage=但在过去的几个小时里,我无法找到它
若我只是在循环完成后将其设置为空值,那个么它将不再刮取其他页面
感谢您花时间阅读此问题,如有任何反馈,我们将不胜感激。在for循环外部声明或重置tempNextPage变量,并在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 :
....
很好,非常感谢你浏览我的集群。实际上,只要在FOR循环之外重置它就足够了,但是如果我添加了check if not,我就会得到soup3.find_all的错误消息。然而,如果没有它,它工作得很好,仍然希望找到一种方法,使它不在一个庞大的嵌套循环中,但现在绝对有效。非常感谢。