来自所有搜索结果页面的数据抓取信息

时间:2016-06-02 16:09:38

标签: ruby-on-rails ruby web-scraping nokogiri mechanize

我正试图从UCAS网站抓取数据,以显示从基本搜索中返回的所有页面中的所有Uni名称。

到目前为止,如果没有循环工作,它会显示第一页所有大学的名称以及一些随机信息,如下所示:

"The University of Aberdeen
Abertay University
Aberystwyth University
ABI College
Abingdon and Witney College
The Academy of Contemporary Music
Access to Music
Accrington & Rossendale College
Activate Learning (Oxford, Reading, Banbury & Bicester)
The College of Agriculture, Food and Rural Enterprise
Amersham & Wycombe College
Amsterdam Fashion Academy
Anglia Ruskin University
Anglo European College of Chiropractic
Arden University (RDI)
University of the Arts London
Arts University Bournemouth (formerly University College)
ARU London
Askham Bryan College
Aston University, Birmingham
Availability
Applying through Extra
Single/Combined subjects
Provider types
How you study
Qualification level
Conservatoire specialism"

这是我的代码:

require 'rubygems' 
require 'nokogiri'  
require 'open-uri'  
require 'mechanize'

mechanize = Mechanize.new

doc = mechanize.get('http://search.ucas.com/')

form = doc.forms.first

form['Vac'] = '2'  
form['AvailableIn'] = '2016'  
doc = form.submit
doc.search('li.results clearfix').each do |h3|  
  puts h3.text.strip  


  while a = doc.at('div.pagerclearfix a')   
    doc = Nokogiri::HTML(open(a[:href]))    
    doc.search('results clearfix').each do |h3|    
      puts h3.text.strip   

    end 
  end 
end

1 个答案:

答案 0 :(得分:0)

你不需要require 'rubygems',因为这是一种反模式。您不需要require 'nokogiri',因为它是Mechanize所要求的,并且您不需要OpenURI。

分页无效,因为div.pagerclearfix选择器与任何内容都不匹配,因为pagerclearfix是单独的类。 while循环也在错误的位置,它不应该在打印结果的each循环内。

你最终应该得到的是:

require 'mechanize'

mechanize = Mechanize.new

page = mechanize.get('http://search.ucas.com/')

form = page.forms.first
form['Vac'] = '2'
form['AvailableIn'] = '2016'

page = form.submit

page.search('li.result h3').each do |h3|
  puts h3.text.strip
end

while next_page_link = page.at('.pager a[text()=">"]')
  page = mechanize.get(next_page_link['href'])

  page.search('li.result h3').each do |h3|
    puts h3.text.strip
  end
end

有多种方法可以实现分页,搜索“下一页”链接通常是最直接的。