如何在Nokogiri中将相对链接转换为绝对链接?附转换示例
Modifying Links with Nokogiri to Add a Custom Prefix
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.pdfandfoo/ba.pdfbecomePREFIX/foo/ba.pdf(no duplicate slashes). - Leaving other links untouched: Full URLs like
http://google.com/foo/ba.pdfand anchors like#helloremain 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_htmlvariable with your actual HTML content.
内容的提问来源于stack exchange,提问作者somenxavier
相关产品推荐
相关产品推荐

