相反操作使用普通字符串操作的URL字符串,用于作业的制作工具。红宝石包括URI类,并有更彻底的Addressable宝石。
这里的,如果我有一些HTML的链接,我想重写我会怎么做:
首先,解析文档:
require 'nokogiri'
require 'uri'
SOURCE_SITE = "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)
if uri.relative?
uri.scheme = SOURCE_SITE.scheme
uri.host = SOURCE_SITE.host
node[url_param] = uri.to_s
end
end
end
puts doc.to_html
其中,运行后,输出s:
<!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=US-ASCII"></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>
这并不意味着它是一个完整的,完整的例子。这是与绝对链接,但你必须处理相对链接,与兄弟/同行主机名的链接,缺少参数。
您还需要在解析后检查“doc”的errors
方法,以确保它是有效的HTML。解析器可以重写/修剪无效HTML中的节点,试图理解它。
你应该考虑使用专门为工作而设计的工具:[URI(HTTP://www.ruby-doc。组织/ STDLIB-1.9.3/libdoc/URI /的RDoc/URI.html)。它有方法来解析URL,更改方案和主机,混淆路径,然后吐出一个正确编码的字符串。 – 2013-04-08 23:58:14
@theTinMan我喜欢这个想法,如果你把它作为一个答案,我会高兴地接受它。 – Noz 2013-04-09 16:42:46
我添加了一个扩展的例子。 – 2013-04-09 19:28:08