在轨道上用nokogiri和ruby更改href属性

Joa*_*ira 17 html string parsing ruby-on-rails nokogiri

我有一个带链接链接的HTML文档,例如:

<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>
Run Code Online (Sandbox Code Playgroud)

我希望使用Ruby on Rails,使用nokogiri或其他方法来获得这样的最终文档:

<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>
Run Code Online (Sandbox Code Playgroud)

实现这一目标的最佳策略是什么?

jde*_*eno 31

如果你选择使用Nokogiri,我认为这应该有效:

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'))
Run Code Online (Sandbox Code Playgroud)

如果我没有弄错的话,默认情况下rails会加载REXML,这取决于你想要做什么,你也可以使用它.

  • `link ['href']`是`link.attributes ["href"].value`的快捷方式 (2认同)