我使用Rails 5和Ruby 4.2并扫描我用Nokogiri解析的文档,以不区分大小写的方式查找带有文本的链接:
a_elt = doc ? doc.xpath('//a').detect { |node| /link[[:space:]]+text/i === node.text } : nil
在content
获取我的网页的HTML后,我使用以下方法将其解析为Nokogiri文档:
doc = Nokogiri::HTML(content)
问题是,我正在
ArgumentError invalid byte sequence in UTF-8
使用上述正则表达式时,在某些网页上。
2.4.0 :002 > doc.encoding
=> "UTF-8"
2.4.0 :003 > doc.xpath('//a').detect { |node| /individual[[:space:]]+results/i === node.text }
ArgumentError: invalid byte sequence in UTF-8
from (irb):3:in `==='
from (irb):3:in `block in irb_binding'
from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/nokogiri-1.7.0/lib/nokogiri/xml/node_set.rb:187:in `block in each'
from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/nokogiri-1.7.0/lib/nokogiri/xml/node_set.rb:186:in `upto'
from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/nokogiri-1.7.0/lib/nokogiri/xml/node_set.rb:186:in `each'
from (irb):3:in `detect'
from (irb):3
from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/commands/console.rb:65:in `start'
from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/commands/console_helper.rb:9:in `start'
from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:78:in `console'
from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:49:in `run_command!'
from /Users/davea/.rvm/gems/ruby-2.4.0@global/gems/railties-5.0.1/lib/rails/commands.rb:18:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
有没有办法可以重写上面的内容来自动解释编码或奇怪的字符,而不是翻出来?
答案 0 :(得分:4)
之前您的问题可能已经得到解答。您是否尝试过&#34; Is there any way to clean a file of "invalid byte sequence in UTF-8" errors in Ruby?&#34;?
中的方法特别是在detect
块之前,尝试删除除新行之外的无效字节和控制字符:
doc.scrub!("")
doc.gsub!(/[[:cntrl:]&&[^\n\r]]/,"")
请注意,scrub!
是Ruby 2.1+ method。