使用Nokogiri更换时的编码问题 [英] Encoding issue when using Nokogiri replace

查看:165
本文介绍了使用Nokogiri更换时的编码问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

# encoding: utf-8
require 'nokogiri'

s = "<a href='/path/to/file'>Café Verona</a>".encode('UTF-8')
puts "Original string: #{s}"

@doc = Nokogiri::HTML::DocumentFragment.parse(s)

links = @doc.css('a')
only_text = 'Café Verona'.encode('UTF-8')
puts "Replacement text: #{only_text}"
links.first.replace(only_text)
puts @doc.to_html

但是,输出是:

Original string: <a href='/path/to/file'>Café Verona</a>
Replacement text: Café Verona
Café Verona

@doc 最后是错误的编码?

'UTF-8')或使用文档而不是 DocumentFragment 问题。

I tried with and without encode('UTF-8') or using Document instead of DocumentFragment, but it's the same problem.

我在Ruby 1.9.3p194上使用Nokogiri v1.5.6。

I'm using Nokogiri v1.5.6 with Ruby 1.9.3p194.

推荐答案

似乎如果你通过一个nokogiri文本对象它做的事);

Seems that if you pass a nokogiri text object it does the thing ;)

links.first.replace Nokogiri::XML::Text.new(only_text, @doc)

这篇关于使用Nokogiri更换时的编码问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆