2012-11-21 2 views
2

저는 python을 처음 사용하고 여러 페이지가있는 페이지의 모든 링크를 가져 오기 위해 스크래퍼를 작성하려고합니다. 다음 코드를 while 루프에서 호출합니다.while 루프에서 호출하면 Beautifulsoup이 반환됩니다.

page = urllib2.urlopen(givenurl,"",10000) 

soup = BeautifulSoup(page, "lxml") 

linktags = soup.findAll('span',attrs={'class':'paginationLink pageNum'}) 

page.close() 

BeautifulSoup.clear(soup) 

return linktags 

항상 통과 한 첫 번째 URL의 결과를 반환합니다. 내가 뭐 잘못하고 있니?

+1

루프를 호출하는 방법을 보여줄 수 있습니까? URL이 다른가 확실합니까? – jdi

+3

루프 내에 리턴 값이있는 경우 두 번 이상 반복하지 않습니다. –

+0

@uncollected : 나는 당신이 그것을 못 박았 겠지. – jdi

답변

5

아마도 @uncollected가 댓글에 당신에게 옳은 대답을 주었을 것입니다. 그러나 나는 그것을 확장하고 싶었습니다.

정확한 코드를 사용하고 있지만 while 블록에 중첩되어 있으면 바로 첫 번째 결과로 돌아갑니다. 여기서 두 가지 일을 할 수 있습니다.

자신의 상황에서 while을 어떻게 사용하고 있는지 잘 모르겠습니다. 여기서는 for 루프를 사용하고 있습니다.

당신이 그것을 generator, using the yield keyword 할 수 있습니다, 결과 목록을 확장하고 반환하는

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 

또는 대신 전체 목록을 반환합니다. 생성기는 각 결과를 반환하고 다음 루프까지 일시 중지합니다.

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 
관련 문제