1

我正在使用 Nokogiri 解析 HTML 文档。该代码包含几个这样的图像:

 <a href="http://url_to_big_photo.jpg"><img alt="alternative-text" border="0" height="427" src="http://url_to_my_photo.jpg?" title="Image Title" width="640"></a>

我正在尝试将该图像保存到我的 S3 存储中,更改样式并删除链接。所有图像都有 css 标签“.post-body img”。

到目前为止,我得到的最接近的是:

@doc.css(".post-body img").each do |image|
    @new_photo = Photo.create!(
       #Params required to save and upload the photo to S3.
        ...
        ...
       )
     # The url of the photo upload to S3 is @new_photo.photo.url
    image['src']= @new_photo.photo.url
    image['class'] = "my-picture-class"
    image.parent['src] = '#'
    puts image.parent.content
    @doc.to_html
  end

这会删除大照片的链接,但显然这不是一个好的解决方案。

我尝试使用http://rubyforge.org/pipermail/nokogiri-talk/2009-June/000333.html上的建议使用 image.parent << image 替换父级,但没有做任何事情和 image.parent =图像返回“无法重新父节点(RuntimeError)”

4

1 回答 1

1

要将该邮件列表示例转换为适用于您的情况,您必须记住这node是他们试图摆脱的节点,在您的情况下是image.parent.

因此,image.parent['src] = '#'您应该尝试:

link = image.parent
link.parent << image
link.remove

编辑:

实际上,上面的代码可能会将所有图像移动到包含链接的任何元素的底部,所以试试这个:

link = image.parent
link.replace(image)
于 2012-10-06T17:03:29.203 回答