加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 如何让Mechanize自动将body转换为UTF8?

发布时间:2020-12-17 02:35:00 所属栏目:百科 来源:网络整理
导读:我找到了一些使用post_connect_hook和pre_connect_hook的解决方案,但似乎它们不起作用.我正在使用最新的Mechanize版本(2.1).新版本中没有[:response]字段,我不知道在新版本中将它们放到哪里. https://gist.github.com/search?q=pre_connect_hooks https://g
我找到了一些使用post_connect_hook和pre_connect_hook的解决方案,但似乎它们不起作用.我正在使用最新的Mechanize版本(2.1).新版本中没有[:response]字段,我不知道在新版本中将它们放到哪里.

> https://gist.github.com/search?q=pre_connect_hooks
> https://gist.github.com/search?q=post_connect_hooks

是否有可能使Mechanize返回UTF8编码版本,而不必使用iconv手动转换它?

解决方法

从Mechanize 2.0开始,pre_connect_hooks()和post_connect_hooks()的参数发生了变化.

请参阅Mechanize文档:

pre_connect_hooks()

A list of hooks to call before retrieving a response. Hooks are called with the agent,the URI,the response,and the response body.

post_connect_hooks()

A list of hooks to call after retrieving a response. Hooks are called with the agent,and the response body.

现在您无法更改内部response-body值,因为参数不是数组.所以,下一个最好的方法是用你自己的内部解析器替换:

class MyParser
  def self.parse(thing,url = nil,encoding = nil,options = Nokogiri::XML::ParSEOptions::DEFAULT_HTML,&block)
    # insert your conversion code here. For example:
    # thing = NKF.nkf("-wm0X",thing).sub(/Shift_JIS/,"utf-8") # you need to rewrite content charset if it exists.
    Nokogiri::HTML::Document.parse(thing,url,encoding,options,&block)
  end
end

agent = Mechanize.new
agent.html_parser = MyParser
page = agent.get('http://somewhere.com/')
...

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读