需要建立一个网址,并与返回的结果
我想从一个小脚本开始取得我和我的朋友从我们的university website的考试结果。需要建立一个网址,并与返回的结果
我想通过它作为后参数的卷号和处理返回的数据, 我不知道如何创建后字符串。
如果有人能告诉我该从哪里开始,要学什么东西,那么将非常赞赏指南的链接。
我不想让别人为我写代码,只是指导如何开始。
我已经在这里写了一个解决方案,只是作为您可能想出的任何参考。攻击有多种方式。
#fetch_scores.rb
require 'open-uri'
#define a constant named URL so if the results URL changes we don't
#need to replace a hardcoded URL everywhere.
URL = "http://www.nitt.edu/prm/ShowResult.html?¶m="
#checking the count of arguments passed to the script.
#it is only taking one, so let's show the user how to use
#the script
if ARGV.length != 1
puts "Usage: fetch_scores.rb student_name"
else
name = ARGV[0] #could drop the ARGV length check and add a default using ||
# or name = ARGV[0] || nikhil
results = open(URL + name).read
end
你可能会检查Nokogiri或Hpricot用以更好地剖析/格式的结果。 Ruby是一种“隐式返回”语言,所以如果您碰巧想知道为什么我们没有返回语句,那是因为脚本自上次执行后返回结果。
你可以看看net/http库,作为标准库的一部分。有关详细信息,请参阅http://www.ruby-doc.org/stdlib/libdoc/net/http/rdoc/index.html,在该页面上有一些示例可帮助您入门。
Youǘe指出我在正确的方向,谢谢。 – nikhil 2011-06-07 12:45:05
一个非常简单的方式做,这是使用open-uri
库,只是把查询参数的URL查询字符串:
require 'open-uri'
name = 'nikhil'
results = open("http://www.nitt.edu/prm/ShowResult.html?¶m=#{name}").read
results
现在包含正文从URL中取出。
如果你正在寻找更有雄心的东西,看看net/http
和httparty
宝石。
这看起来像我想要的,但那里的形式需要POST数据,通过这种方式传递参数导致404页面未找到错误。 如何以这种方式创建HTTP POST请求? – nikhil 2011-06-07 05:48:34
你会想看看[这个](http://ruby-doc.org/stdlib/libdoc/net/http/rdoc/classes/Net/HTTP.html)并改变使用'open-uri'用'net/http'。不幸的是Open-uri只是让你使用'GET'。你可能需要'net/http'的方法是:'Net :: HTTP.post_form'。这些例子看起来也是在利用'URI'。应该有足够的示例代码在该页面上让你工作。 – 2011-06-07 11:34:40
谢谢,我已经取得了一些进展,希望我能尽快完成这项工作。 谢谢。 – nikhil 2011-06-07 12:44:24