Changing href attributes with nokogiri and ruby on rails

前端 未结 2 755
野性不改
野性不改 2021-02-05 09:45

I Have a HTML document with links links, for exemple:


  
   
相关标签:
2条回答
  • 2021-02-05 10:27

    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'))
    

    If I'm not mistaken rails loads REXML up by default, depending on what you're trying to do you could use this also.

    0 讨论(0)
  • 2021-02-05 10:28

    Here is what I did for replacing images src attributes:

          doc = Nokogiri::HTML(html)
           doc.xpath("//img").each do |img|
             img.attributes["src"].value = Absolute_asset_path(img.attributes["src"].value)
          end
          doc.to_html                  // simply use .to_html to re-convert to html
    
    0 讨论(0)
提交回复
热议问题