不要使用普通的字符串操作来操作 URL 字符串,而是使用专门为该工作制作的工具。红宝石包括URI http://www.ruby-doc.org/stdlib-1.9.3/libdoc/uri/rdoc/URI.html类,还有更彻底的可寻址 https://github.com/sporkmonger/addressable gem.
如果我有一些带有我想要重写的链接的 HTML,我会这样做:
首先,解析文档:
require 'nokogiri'
require 'uri'
SOURCE_SITE = URI.parse("http://virtualrobotgames.com")
html = '
<html>
<head></head>
<body>
<img src="/system/images/146/original/03.png?1362691463">
<script src="/scripts/foo.js"></script>
<a href="/foo/bar.html">foo</a>
</body>
</html>
'
doc = Nokogiri::HTML(html)
然后您就可以浏览文档并修改标签,例如<a>
, <img>
, <script>
以及您想要的任何其他内容:
# find things using 'src' and 'href' parameters
tags = {
'img' => 'src',
'script' => 'src',
'a' => 'href'
}
doc.search(tags.keys.join(',')).each do |node|
url_param = tags[node.name]
src = node[url_param]
unless (src.empty?)
uri = URI.parse(src)
unless uri.host
uri.scheme = SOURCE_SITE.scheme
uri.host = SOURCE_SITE.host
node[url_param] = uri.to_s
end
end
end
puts doc.to_html
运行后输出:
# >> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
# >> <html>
# >> <head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head>
# >> <body>
# >> <img src="http://virtualrobotgames.com/system/images/146/original/03.png?1362691463">
# >> <script src="http://virtualrobotgames.com/scripts/foo.js"></script>
# >> <a href="http://virtualrobotgames.com/foo/bar.html">foo</a>
# >> </body>
# >> </html>
这并不是一个完整的、完全有效的示例。这适用于绝对链接,但您必须处理相对链接、具有同级/对等主机名的链接、缺少参数。
您还需要检查errors
解析后的“doc”方法,以确保它是有效的 HTML。解析器可以重写/修剪无效 HTML 中的节点,试图理解它。