这是一个简单的脚本,它采用其中包含德语 URL 的 anchor 标记,并提取 URL:
# encoding: utf-8
require 'uri'
url = URI.extract('<a href="http://www.example.com/wp content/uploads/2012/01/München.jpg">München</a>')
puts url
http://www.example.com/wp-content/uploads/2012/01/M
extract
方法在 ü
处停止。我怎样才能让它与非英文字母一起使用?我正在使用 ruby-1.9.3-p0。
最佳答案
Ruby 的内置 URI 在某些方面很有用,但在处理国际字符或 IDNA 地址时,它并不是最佳选择。为此,我建议使用 Addressable gem 。
这是一些清理后的 IRB 输出:
require 'addressable/uri'
url = 'http://www.example.com/wp content/uploads/2012/01/München.jpg'
uri = Addressable::URI.parse(url)
这是 Ruby 现在知道的:
#<Addressable::URI:0x102c1ca20
@uri_string = nil,
@validation_deferred = false,
attr_accessor :authority = nil,
attr_accessor :host = "www.example.com",
attr_accessor :path = "/wp content/uploads/2012/01/München.jpg",
attr_accessor :scheme = "http",
attr_reader :hash = nil,
attr_reader :normalized_host = nil,
attr_reader :normalized_path = nil,
attr_reader :normalized_scheme = nil
>
查看路径,您可以看到它的原样或应该的样子:
1.9.2-p290 :004 > uri.path # => "/wp content/uploads/2012/01/München.jpg"
1.9.2-p290 :005 > uri.normalized_path # => "/wp%20content/uploads/2012/01/M%C3%BCnchen.jpg"
考虑到互联网如何转向更复杂的 URI 和混合的 Unicode 字符,确实应该选择 Addressable 来替换 Ruby 的 URI。
现在,获取字符串也很容易,但这取决于您必须查看多少文本。
如果您有完整的 HTML 文档,最好的办法是使用 Nokogiri解析 HTML 并提取 href
来自 <a>
的参数标签。这是单个 <a>
的起点:
require 'nokogiri'
html = '<a href="http://www.example.com/wp content/uploads/2012/01/München.jpg">München</a>'
doc = Nokogiri::HTML::DocumentFragment.parse(html)
doc.at('a')['href'] # => "http://www.example.com/wp content/uploads/2012/01/München.jpg"
使用 DocumentFragment
解析避免将片段包裹在通常的 <html><body>
中标签。对于您想要使用的完整文档:
doc = Nokogiri::HTML.parse(html)
两者的区别:
irb(main):006:0> Nokogiri::HTML::DocumentFragment.parse(html).to_html
=> "<a href=\"http://www.example.com/wp%20content/uploads/2012/01/M%C3%BCnchen.jpg\">München</a>"
对比:
irb(main):007:0> Nokogiri::HTML.parse(html).to_html
=> "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<html><body><a href=\"http://www.example.com/wp%20content/uploads/2012/01/M%C3%BCnchen.jpg\">München</a></body></html>\n"
因此,对于完整的 HTML 文档使用第二种,对于小的部分块,使用第一种。
要扫描整个文档,提取所有 href,请使用:
hrefs = doc.search('a').map{ |a| a['href'] }
如果您只有示例中显示的小字符串,您可以考虑使用简单的正则表达式来隔离所需的 href
:
html[/href="([^"]+)"/, 1]
=> "http://www.example.com/wp content/uploads/2012/01/München.jpg"
关于ruby-on-rails - 如何从字符串中提取包含非英文字符的 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9082732/