【问题标题】:How to search in page body and force an encoding conversion如何在页面正文中搜索并强制进行编码转换
【发布时间】:2017-04-11 10:24:31
【问题描述】:

我有非常简单的代码:

require 'rubygems'
require 'mechanize'

URL = 'http://yandex.ru'

agent = Mechanize.new
page = agent.get(URL)

# page.encoding => UTF-8
# page.body.encoding => ASCII-8BIT

page.body.include?("Карты")

在该代码的最后一行,Ruby 返回了一个错误:

in `include?': incompatible character encodings: ASCII-8BIT and UTF-8 (Encoding::CompatibilityError)

来自“How to get Mechanize to auto-convert body to UTF8?”的解决方案没有帮助。我应该怎么做才能解决它?

【问题讨论】:

    标签: ruby encoding utf-8 mechanize


    【解决方案1】:

    您可以像这样使用force_encoding 方法:

    agent.page.body.force_encoding('utf-8')
    

    【讨论】:

    猜你喜欢
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    相关资源
    最近更新 更多