2016-06-24 3 views
0

여러 기사가 표시된 쇼핑 페이지에 있습니다. 나는 이미 'links_with'로 얻은 모든 기사 링크를 볼 수 있습니다. 이제 새 기능 내에서 기사 페이지의 콘텐츠를 크롤링하고 싶습니다. 나는 그곳에 갈 수 있지만 그때 하나의 주소 만 가지고 있고 그 내용으로 여러 페이지를 크롤링하고 싶습니다. 배열과 someloops로 이것을 해결할 수있는 방법이 있습니까? 나는 Ruby에 익숙하지 않아 이것을 해결할 수 없었다. 내가 당신을 이해한다면크롤링 된 링크를 배열에 저장 한 다음 해당 내용을 스크랩하는 함수를 호출합니다.

def self.configureCrawler(page_URL) 
    agent = Mechanize.new 
    page = agent.get(page_URL) 

    article_links = page.links_with(href: %r{.*/p/}) #all links with /p/ in address 

    article_links.uniq { |link| link.uri }.each do |link| #no double entries 
    link.click 
    @target_URL = page.uri + link.uri #full url 
    puts "#{@target_URL}" 
    end 

    startCrawler(@target_URL) 
end 


def self.startCrawler(article_URL) #the crawling process itself 
    page = Nokogiri::HTML(open(article_URL)) 

    @id = page.css('CSS STUFF').text. 
    @name = page.css('CSS STUFF').text 
    @price = page.css('CSS STUFF').text 
    #... 

    puts "id: #{@id}" 
    puts "name: #{@name}" 
    puts "price: #{@price}" 
end 

답변

1

바로 당신이 map 대신 each 사용할 수 있습니다.
map 또한 물마루를 반복하지만 반환 값입니다. 이

def self.configureCrawler(page_URL) 
    agent = Mechanize.new 
    page = agent.get(page_URL) 

    article_links = page.links_with(href: %r{.*/p/}) #all links with /p/ in address 

    article_links.uniq { |link| link.uri }.map do |link| #no double entries 
    link.click 
    target_URL = page.uri + link.uri #full url 
    puts "#{target_URL}" 
    startCrawler target_URL 
    end 
end 

같은

시도 뭔가 self.configureCrawlerstartCrawler 호출의 결과 배열을 반환합니다 이쪽으로.
또한 self.startCrawler (@ 삭제)에서 인스턴스 변수를 사용할 필요가 없습니다.

def self.startCrawler(article_URL) #the crawling process itself 
    page = Nokogiri::HTML(open(article_URL)) 

    id = page.css('CSS STUFF').text. 
    name = page.css('CSS STUFF').text 
    price = page.css('CSS STUFF').text 

    puts "id: #{id}" 
    puts "name: #{name}" 
    puts "price: #{price}" 

    { id: id, name: name, price: price } # do not forget to return value, for example such hash 
end 
+0

고맙습니다! 그러나 startCrawler 메서드에있을 때 배열의 한 페이지 (article_URL을 인쇄 할 때) 만 남았습니다. 해당 콘텐츠가 포함 된 모든 페이지를 크롤링하고 싶습니다. 어디에서 루프를 시작해야합니까? – GoYoshi

+0

이렇게 될 수는 없습니다. 'startCrawler'는'uniq' 이후에'article_links '의 모든 요소와 함께 호출 될 것입니다. – Aleksey