2017-04-25 7 views
1

でページのレンダリング方法のWebスクレイプmuliple JavaScriptにこれは、検索結果はJavaScriptによってレンダリングされているので、私はのRuby on Railsとワチール

https://www.cargurus.com/Cars/inventorylisting/viewDetailsFilterViewInventoryListing.action?sourceContext=carGurusHomePage_false_0&formSourceTag=104&entitySelectingHelper.selectedEntity=m2&zip=48126#resultsPage=1 

の結果を取得しようとしていますページで、私が使用する必要がありますWebDriver Watir。私は最初の5ページの結果を得たいと思います。しかし、私は最初のページだけを取得でき、他のページは取得できません。他のページはどのように訪問するのですか?

$pageCount = 1 

5.times do 
       page = $pageCount.to_s 
       browser = Watir::Browser.start("https://www.cargurus.com/Cars/inventorylisting/viewDetailsFilterViewInventoryListing.action?sourceContext=carGurusHomePage_false_0&formSourceTag=104&entitySelectingHelper.selectedEntity=m2&zip=48126#resultsPage=#{page}", browser = :phantomjs) 
       #browser.link(:class, "nextPageElement").wait_until_present 
       doc = Nokogiri::HTML.parse(browser.html) 
        entries = doc.css('.cg-dealFinder-result-wrap') 
        entries.each do |entry| 
          title = entry.css('.cg-dealFinder-result-model>span')[0].text.strip 
          link = entry.css('.cg-dealFinder-result-stats>p>span')[0].text.strip 
          newEntry = Entry.new(title: title, description:link) 
          if title.present? && link.present? && Entry.where(title: title, description: link).blank? 
          newEntry.save 
          end 
        end 
       $pageCount = $pageCount + 1 
       browser.close 
     end 

Btw私は、JavaScriptでレンダリングされていないページの結果を持つ他のウェブサイトに対して、複数のスクレイプを正常に実行できます。

+0

基本となるリクエストのjsonレスポンスを解析する方法はありますか?ページがロードされた直後にリクエスト 'ajaxFetchSubsetInventoryListing'を探します。投稿したURLは、対応するパラメータとともにAjax POSTリクエストを作成します。 –

答えて

0

ページ数を表す範囲(または配列)を作成する場合は、ページ番号をBrowser::gotoメソッドに反復して渡し、Browser::htmlメソッドを使用してページを擦ったり、収集しようとしているデータを対象にすることができます。

require 'watir' 

b = Watir::Browser.new :chrome 

(1..5).each do |num| 
    b.goto "https://www.cargurus.com/Cars/inventorylisting/viewDetailsFilterViewInventoryListing.action?sourceContext=carGurusHomePage_false_0&formSourceTag=104&entitySelectingHelper.selectedEntity=m2&zip=48126#resultsPage=#{num}" 
    puts b.div(:id => "displayedListingsCount").text # or puts b.html 
end  
b.close 

#=> Showing 1 - 15 out of 2000 listings 
#=> Showing 16 - 30 out of 2000 listings 
#=> Showing 31 - 45 out of 2000 listings 
#=> Showing 46 - 60 out of 2000 listings 
#=> Showing 61 - 75 out of 2000 listings