【问题标题】:Convert URLs in HTML document?转换 HTML 文档中的 URL?
【发布时间】:2011-07-17 07:53:07
【问题描述】:

我在 foo.com 上有一个 HTML 文档,其中包含链接、表单、资产 URL(图像/JavaScript)。

我想在 bar.com 上提供不带框架的服务。我还希望将所有相对 URL 转换为主机名为“bar.com”的绝对 URL、资产 URL 和表单操作 URL。

我从 foo.com 获取了 HTML 文档。使用 Nokogiri 转换其中的 URL 的下一步是什么?

【问题讨论】:

    标签: ruby regex url nokogiri


    【解决方案1】:

    Nokogiri 是一个 HTML/XML 解析器。您可以关注official tutorial 了解如何解析您的文档。

    这是一个例子:

    require 'rubygems'
    require 'nokogiri'
    # Open the remote document, or from local file
    require 'open-uri' # load open-uri library if the input is from the Internet
    doc = Nokogiri::HTML(open(URL_OR_PATH_TO_DOCUMENT))
    
    # Search for img tags:
    doc.css('img').each do |img|
      # modify its attribute
      img['src'] = "#{URL_PREFIX}/#{img['src']}"
    end
    
    # print the modified html
    puts doc.to_html
    

    【讨论】:

      【解决方案2】:
      require 'nokogiri'
      require 'open-uri'
      
      url = 'http://www.google.com'
      doc = Nokogiri::HTML(open(url))
      doc.xpath('//a').each do |d|
        rel_url = d.get_attribute('href')
        d.set_attribute('href', 'http://www.xyz.com/' + rel_url)
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-20
        • 2016-03-19
        • 2017-08-25
        • 2014-04-04
        相关资源
        最近更新 更多