@uncollected可能在评论中对您有正确的答案,但我想对其进行扩展。
如果您要求确切的代码,但嵌套在while
块中,它将立即返回第一个结果。你可以在这里做两件事。
我不确定您在自己的环境中如何使用while
,所以我在此处使用for
循环。
扩展结果列表,并返回
def getLinks(urls):
""" processes all urls, and then returns all links """
links = []
for givenurl in urls:
page = urllib2.urlopen(givenurl,"",10000)
soup = BeautifulSoup(page, "lxml")
linktags = soup.findAll('span',attrs={'class':'paginationLink pageNum'})
page.close()
BeautifulSoup.clear(soup)
links.extend(linktags)
# dont return here or the loop is over
return links
或者,而不是返回的整个列表,你可以把它generator, using the yield
keyword。生成器将返回每个结果并暂停,直到下一个循环:
def getLinks(urls):
""" generator yields links from one url at a time """
for givenurl in urls:
page = urllib2.urlopen(givenurl,"",10000)
soup = BeautifulSoup(page, "lxml")
linktags = soup.findAll('span',attrs={'class':'paginationLink pageNum'})
page.close()
BeautifulSoup.clear(soup)
# this will return the current results,
# and pause the state, until the the next
# iteration is requested
yield linktags
来源
2012-11-21 01:38:13
jdi
你能说明你是如何调用循环的吗?你确定这个网址是不同的吗? – jdi
如果循环内有回车,它将不会迭代多次。 –
@uncollected:我敢打赌你只是钉了它 – jdi