使用nokogiri和ruby在rails上更改href属性 [英] Changing href attributes with nokogiri and ruby on rails
本文介绍了使用nokogiri和ruby在rails上更改href属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有链接链接的HTML文档,例如:
I Have a HTML document with links links, for exemple:
<html>
<body>
<ul>
<li><a href="http://someurl.com/etc/etc">teste1</a></li>
<li><a href="http://someurl.com/etc/etc">teste2</a></li>
<li><a href="http://someurl.com/etc/etc">teste3</a></li>
<ul>
</body>
</html>
我希望使用Ruby on Rails,使用nokogiri或其他方法来获得最终的文档:
I want with Ruby on Rails, with nokogiri or some other method, to have a final doc like this:
<html>
<body>
<ul>
<li><a href="http://myproxy.com/?url=http://someurl.com/etc/etc">teste1</a></li>
<li><a href="http://myproxy.com/?url=http://someurl.com/etc/etc">teste2</a></li>
<li><a href="http://myproxy.com/?url=http://someurl.com/etc/etc">teste3</a></li>
<ul>
</body>
</html>
最佳策略是什么?
What's the best strategy to achieve this?
推荐答案
如果您选择使用Nokogiri,我认为这应该起作用:
If you choose to use Nokogiri, I think this should work:
require 'cgi'
require 'rubygems' rescue nil
require 'nokogiri'
file_path = "your_page.html"
doc = Nokogiri::HTML(open(file_path))
doc.css("a").each do |link|
link.attributes["href"].value = "http://myproxy.com/?url=#{CGI.escape link.attributes["href"].value}"
end
doc.write_to(open(file_path, 'w'))
如果我不是错误的rails会默认加载REXML,这取决于你想要做什么,你也可以使用它。
If I'm not mistaken rails loads REXML up by default, depending on what you're trying to do you could use this also.
这篇关于使用nokogiri和ruby在rails上更改href属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文