我使用OpenURI库.
object = open("http://example.com")
Run Code Online (Sandbox Code Playgroud)
如果http://example.com服务器代码响应等于200,我的程序就像我预期的那样.但是,如果http://example.com服务器响应代码等于400(或其他),则脚本将以OpenURI :: HTTPError中止:404 Not Found.
如果我使用'begin-rescue'构造并处理'HTTPError exception',我可以避免这种情况.
这是正确的方法吗?我应该使用Net/Http库而不是OpenURI来处理所有情况吗?
在Ruby中我有三个嵌套循环:
array.each do |a|
array.each do |b|
array.each do |c|
puts a * b * c
end
end
end
Run Code Online (Sandbox Code Playgroud)
如果嵌套循环的数量可以增加到5-10次并且更多迭代,我该如何优化此代码?
例:
array.each do |a|
array.each do |b|
array.each do |c|
array.each do |d|
array.each do |e|
array.each do |f|
puts a * b * c * d * e * f
end
end
end
end
end
end
Run Code Online (Sandbox Code Playgroud) 我有一些网站,例如http://example.com
我想生成一个站点地图作为URI列表,例如:
http://example.com/mainhttp://example.com/tagshttp://example.com/tags/foohttp://example.com/tags/bar我找到了一个很好的应用程序:iGooMap
iGooMap可以生成所需的URI列表作为文本文件(而不是XML文件).
这是我想要实现的目标的直观表示:
我希望在Ruby(而不是 Rails)中生成这种类型的站点地图.
我找到了SiteMapGenerator,但它只生成一个.XML文件,但是如上所述,我需要一个文本文件.
是否有Ruby的解决方案为给定的站点创建链接列表?
我有一个模块,可以生成我需要的格式的电话号码.
module PhoneNumber
def self.prefix
'+'
end
def self.country
rand(1..9).to_s
end
def self.code
rand(100..999).to_s
end
def self.number
rand(1000000..9999999).to_s
end
end
Run Code Online (Sandbox Code Playgroud)
我用它如下.或者作为格式化字符串"#{}#{}".
phone_number = PhoneNumber.prefix +
PhoneNumber.country +
PhoneNumber.code +
PhoneNumber.number
Run Code Online (Sandbox Code Playgroud)
我想以这种方式重写模块的主体,以便我可以以点分格式使用它.
PhoneNumber.prefix.code.number
Run Code Online (Sandbox Code Playgroud) 我需要从网站的所有页面收集所有"标题".
站点具有HTTP基本身份验证配置.
没有auth我接下来做:
require 'anemone'
Anemone.crawl("http://example.com/") do |anemone|
anemone.on_every_page do |page|
puts page.doc.at('title').inner_html rescue nil
end
end
Run Code Online (Sandbox Code Playgroud)
但是我对HTTP Basic Auth有一些问题...
我如何使用HTTP Basic Auth从站点收集标题?
如果我尝试使用"Anemone.crawl(" http:// username:password@example.com/ ")",那么我只有第一页标题,但其他链接有http://example.com/风格,我收到401错误.
ruby ×5
anemone ×1
gem ×1
module ×1
nested-loops ×1
net-http ×1
open-uri ×1
optimization ×1
sitemap ×1
web-crawler ×1