【发布时间】:2011-07-17 07:53:07
【问题描述】:
我在 foo.com 上有一个 HTML 文档,其中包含链接、表单、资产 URL(图像/JavaScript)。
我想在 bar.com 上提供不带框架的服务。我还希望将所有相对 URL 转换为主机名为“bar.com”的绝对 URL、资产 URL 和表单操作 URL。
我从 foo.com 获取了 HTML 文档。使用 Nokogiri 转换其中的 URL 的下一步是什么?
【问题讨论】:
我在 foo.com 上有一个 HTML 文档,其中包含链接、表单、资产 URL(图像/JavaScript)。
我想在 bar.com 上提供不带框架的服务。我还希望将所有相对 URL 转换为主机名为“bar.com”的绝对 URL、资产 URL 和表单操作 URL。
我从 foo.com 获取了 HTML 文档。使用 Nokogiri 转换其中的 URL 的下一步是什么?
【问题讨论】:
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
【讨论】:
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
【讨论】: