You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Nokogiri中将相对链接转换为绝对链接?附转换示例

Here's a step-by-step guide to achieve exactly what you need using Nokogiri in Ruby:

1. First, install Nokogiri

If you haven't already, install the gem via:

gem install nokogiri

2. Write the code

This script will parse your HTML, target the right links, and update their href attributes with your custom prefix:

require 'nokogiri'

# Your input HTML string
input_html = '<a href="/foo/ba.pdf">A</a> <a href="foo/ba.pdf">B</a> <a href="http://google.com/foo/ba.pdf">A</a> <a href="#hello">A</a>'

# Replace this with your actual custom prefix
CUSTOM_PREFIX = "PREFIX"

# Parse the HTML document
doc = Nokogiri::HTML(input_html)

# Select only the links we need to modify:
# - Exclude full URLs (start with http)
# - Exclude anchor links (start with #)
target_links = doc.xpath("//a[not(starts-with(@href, 'http')) and not(starts-with(@href, '#'))]")

# Update each target link's href
target_links.each do |link|
  current_href = link['href']
  # Remove any leading slash to ensure consistent formatting
  cleaned_path = current_href.sub(/^\//, '')
  # Build the new href with the prefix
  new_href = "#{CUSTOM_PREFIX}/#{cleaned_path}"
  # Set the updated href attribute
  link['href'] = new_href
end

# Extract the modified content (we use inner_html to get just the body content)
modified_html = doc.at('body').inner_html.strip

# Output the result
puts modified_html

3. What this does

  • Targeting the right links: The XPath selector ensures we only touch links that are either root-relative (start with /) or relative (no leading slash), ignoring full external URLs and anchor links.
  • Consistent formatting: By stripping any leading slash from the original path, we ensure both /foo/ba.pdf and foo/ba.pdf become PREFIX/foo/ba.pdf (no duplicate slashes).
  • Leaving other links untouched: Full URLs like http://google.com/foo/ba.pdf and anchors like #hello remain exactly as they are.

Expected Output

When you run the script with CUSTOM_PREFIX = "PREFIX", you'll get:

<a href="PREFIX/foo/ba.pdf">A</a> <a href="PREFIX/foo/ba.pdf">B</a> <a href="http://google.com/foo/ba.pdf">A</a> <a href="#hello">A</a>

Notes

  • If your prefix contains special characters (like spaces or symbols), you might want to URI-encode it using URI.encode_www_form_component(CUSTOM_PREFIX) to ensure valid URLs.
  • This works for both single links and larger HTML documents—just replace the input_html variable with your actual HTML content.

内容的提问来源于stack exchange,提问作者somenxavier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:09:55