ruby 使用Nokogiri将vml标记中的图像src替换为全局可用的图像

iszxjhcz  于 2023-05-22  发布在  Ruby
关注(0)|答案(1)|浏览(93)

是否可以通过Capybara/Nokogiri找到outlook特定的标记?
给定以下标记(erb <% %>标记被处理为常规HTML)

...
<div>
<!--[if gte mso 9]>
    <v:rect
        xmlns:v="urn:schemas-microsoft-com:vml" fill="true" stroke="false"
        style="width:<%= card_width %>px;height:<%= card_header_height %>px;"
    >
        <v:fill type="tile"
            src="<%= avatar_background_url.split('?')[0] %>"
            color="<%= background_color %>" />
        <v:textbox inset="0,0,0,0">
<![endif]-->
<div>

如何获取<v:fill ../>标签列表?(或者如果在条件注解中找到标记是个问题,我最终如何获得整个注解)
我试过以下方法

doc.xpath('//v:fill')

***Nokogiri::XML::XPath::SyntaxError Exception:错误:未定义的命名空间前缀://v:fill

我需要以某种方式注册vml命名空间吗?
编辑-遵循@ThomasWalpole方法

doc.xpath('//comment()').each do |comment_node|
  vml_node_match = /<v\:fill.*src=\"(?<url>http\:[^"]*)"[^>]*\/>/.match(comment_node)
  if vml_node_match
    original_image_uri = URI.parse(vml_node_match['url'])
    vml_tag = vml_node_match[0]
    handle_vml_image_replacement(original_image_uri, comment_node, vml_tag)
  end

我的handle_vml_image_replacement最终调用了以下replace_comment_image_src

def self.replace_comment_image_src(node:, comment:, old_url:, new_url:)
  new_url = new_url.split('?').first # VML does not support URL with query params
  puts "Replacing comment src URL in #{comment} by #{new_url}"
  node.content = node.content.gsub(old_url, new_url)
end

但后来感觉评论实际上不再是“评论”,我有时可以看到HTML好像被转义了...我很可能使用了错误的方法来更改Nokogiri的评论文本?

neekobn8

neekobn81#

下面是我用于电子邮件拦截器的最终代码,感谢@托马斯Walpole和@sschmeck的帮助。
我的目标是将VML标记中的图像(链接到localhost)替换为全球可用的图像,以便使用MOA或Litmus等服务进行测试

doc.xpath('//comment()').each do |comment_node|
  # Note : cannot capture beginning of tag, since it might span across several lines
  src_attr_match = /.*src=\"(?<url>http[s]?\:[^"]*)"[^>]*\/>/.match(comment_node)
  next unless src_attr_match
  original_image_uri = URI.parse(src_attr_match['url'])
  handle_comment_image_replacement(original_image_uri, comment_node)
end

WHich稍后调用(在根据源图像类型选择url替换策略之后):

def self.replace_comment_image_src(node:, old_url:, new_url:)
  new_url = new_url.split('?').first
  node.native_content = node.content.gsub(old_url, new_url)
end

相关问题