gpt4 book ai didi

ruby - 使用 Mechanize 和 Nokogiri 抓取网页并将数据存储在 XML 文档中

转载 作者:行者123 更新时间:2023-12-04 16:22:50 25 4
gpt4 key购买 nike

我正在尝试使用 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
我认为这段代码没问题,但我不希望它只选择 options[0] ,我想让它选择一个选项,然后抓取我需要的所有数据,然后返回页面,然后选择 options[1] ...直到没有更多选项(我猜是迭代)。

最佳答案

the file is treated I think, but it doesnt create an xml file in the specified path.



您的代码中没有任何内容可以创建文件。您打印了一些输出,但不对 open 做任何事情或 write 一份文件。

也许您应该阅读 IOFile文档并查看您如何使用 filepath多变的?

第二个问题是你没有在任何地方调用你的方法。尽管它已定义并且 Ruby 会看到它并解析该方法,但除非您调用该方法,否则它不知道您想用它做什么:
def mechanize_club
...
end

mechanize_club()

关于ruby - 使用 Mechanize 和 Nokogiri 抓取网页并将数据存储在 XML 文档中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30560596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com