카테고리 없음
[루비] 루비에서 재귀 적 방법을 어떻게 사용해야합니까?
필살기쓰세요
2021. 2. 8. 18:55
코드에 몇 가지 문제가 있습니다.
Mechanize.new
두 번 이상 전화하면 안됩니다 .- 문체 관점에서 너무 많은 nil 검사를 수행하고 있습니다.
재귀를 선호하지 않는 한 반복적으로 수행하는 것이 더 쉬울 것입니다.
next_page
메서드가 체인의 모든 링크 페이지를 포함하는 배열을 반환하도록 하려면 다음과 같이 작성할 수 있습니다.
# you should store the mechanize agent as a global variable
Agent = Mechanize.new
# a helper method to DRY up the code
def click_to_next_page(page)
Agent.click(n_page.link_with(:text=>/next/))
end
# repeatedly visits next page until none exists
# returns all seen pages as an array
def get_all_next_pages(n_page)
results = []
np = click_to_next_page(n_page)
results.push(np)
until !np
np = click_to_next_page(np)
np && results.push(np)
end
results
end
# testing it out (i'm not actually running this)
base_url = "http://www.baidu.com/s?wd=intitle:#{URI.encode(WORD)}%20site:sina.com.cn&rn=50&gpc=stf#{URI.encode(TIME)}"
root_page = Agent.get(base_url)
next_pages = get_all_next_pages(root_page)
puts next_pages
출처
https://stackoverflow.com/questions/39929981