使用 Mechanize 和 Nokogiri 抓取网页并将数据存储在 XML 文档中
Scraping a webpage with Mechanize and Nokogiri and storing data in XML doc
我正在尝试使用 Mechanize 和 Nokogiri 抓取网站并将数据存储在 XML 中。我没有设置 Rails 项目,我只使用 Ruby 和 IRB。
我写了这个方法:
def mechanize_club
agent = Mechanize.new
agent.get("http://www.rechercheclub.applipub-fft.fr/rechercheclub/")
form = agent.page.forms.first
form.field_with(:name => 'codeLigue').options[0].select
form.submit
page2 = agent.get('http://www.rechercheclub.applipub-fft.fr/rechercheclub/club.do?codeClub=01670001&millesime=2015')
body = page2.body
html_body = Nokogiri::HTML(body)
codeclub = html_body.search('.form').children("tr:first").children("th:first").to_i
@codeclubs << codeclub
filepath = '/davidgeismar/Documents/codeclubs.xml'
builder = Nokogiri::XML::Builder.new(encoding: 'UTF-8') do |xml|
xml.root {
xml.codeclubs {
@codeclubss.each do |c|
xml.codeclub {
xml.code_ c.code
}
end
}
}
end
puts builder.to_xml
end
我的第一个问题是我不知道如何测试我的代码。
我在我的控制台中调用 ruby webscraper.rb
,我认为文件已处理,但它不会在指定路径中创建 XML 文件。
然后,更具体地说,我很确定这段代码是错误的,因为我没有机会测试它。
基本上我想做的是多次提交表格:
agent = Mechanize.new
agent.get("http://www.rechercheclub.applipub-fft.fr/rechercheclub/")
form = agent.page.forms.first
form.field_with(:name => 'codeLigue').options[0].select
form.submit
我觉得这段代码还可以,但我不希望它只selectoptions[0]
,我希望它select一个选项,然后抓取我需要的所有数据,然后返回页面,然后 select options[1]
... 直到没有更多选项(我猜是迭代)。
我正在尝试使用 Mechanize 和 Nokogiri 抓取网站并将数据存储在 XML 中。我没有设置 Rails 项目,我只使用 Ruby 和 IRB。
我写了这个方法:
def mechanize_club
agent = Mechanize.new
agent.get("http://www.rechercheclub.applipub-fft.fr/rechercheclub/")
form = agent.page.forms.first
form.field_with(:name => 'codeLigue').options[0].select
form.submit
page2 = agent.get('http://www.rechercheclub.applipub-fft.fr/rechercheclub/club.do?codeClub=01670001&millesime=2015')
body = page2.body
html_body = Nokogiri::HTML(body)
codeclub = html_body.search('.form').children("tr:first").children("th:first").to_i
@codeclubs << codeclub
filepath = '/davidgeismar/Documents/codeclubs.xml'
builder = Nokogiri::XML::Builder.new(encoding: 'UTF-8') do |xml|
xml.root {
xml.codeclubs {
@codeclubss.each do |c|
xml.codeclub {
xml.code_ c.code
}
end
}
}
end
puts builder.to_xml
end
我的第一个问题是我不知道如何测试我的代码。
我在我的控制台中调用 ruby webscraper.rb
,我认为文件已处理,但它不会在指定路径中创建 XML 文件。
然后,更具体地说,我很确定这段代码是错误的,因为我没有机会测试它。
基本上我想做的是多次提交表格:
agent = Mechanize.new
agent.get("http://www.rechercheclub.applipub-fft.fr/rechercheclub/")
form = agent.page.forms.first
form.field_with(:name => 'codeLigue').options[0].select
form.submit
我觉得这段代码还可以,但我不希望它只selectoptions[0]
,我希望它select一个选项,然后抓取我需要的所有数据,然后返回页面,然后 select options[1]
... 直到没有更多选项(我猜是迭代)。