【问题标题】:Setting a HTTP user agent with mechanize?使用机械化设置 HTTP 用户代理?
【发布时间】:2014-04-09 16:09:04
【问题描述】:

我在设置user-agent 时遇到了困难。如您所见,我的自定义 user_agent_alias 没有被退回。有人可以解释为什么这不起作用以及我该如何解决这个问题?

require 'rubygems'
require 'mechanize'
require 'nokogiri'

m = Mechanize.new
m.user_agent_alias = 'My Custom User Agent'
page = m.get("http://whatsmyuseragent.com/")
html = Nokogiri::HTML(page.body)
puts html.xpath('//*[(@id = "body_lbUserAgent")]').map(&:content)

下面是返回的“用户代理”(不是我设置的):

机械化/2.7.3 Ruby/2.0.0p353 (http://github.com/sparklemotion/mechanize/)

【问题讨论】:

    标签: ruby mechanize


    【解决方案1】:

    原来问题在于user_agent_alias 需要特定类型。所有可接受的类型如下:

    • Linux 火狐 (3.6.1)
    • Linux Konqueror (3)
    • Linux Mozilla
    • Mac 火狐 (3.6)
    • Mac Mozilla
    • Mac Safari (5)
    • Mac Safari 4
    • 机械化(默认)
    • Windows IE 6
    • Windows IE 7
    • Windows IE 8
    • Windows IE 9
    • Windows Mozilla
    • iPhone (3.0)
    • iPad
    • Android(摩托罗拉 Xoom)

    工作代码:

    require 'rubygems'
    require 'mechanize'
    
    m = Mechanize.new
    m.user_agent_alias = 'Mac Safari 4'
    page = m.get("http://whatsmyuseragent.com/")
    html = Nokogiri::HTML(page.body)
    puts html.xpath('//*[(@id = "body_lbUserAgent")]').map(&:content)
    

    【讨论】:

    • 您始终可以通过以下方式检索支持的 user_agent_aliases 列表:puts Mechanize::AGENT_ALIASES.keys。我的安装返回["Mechanize", "Linux Firefox", "Linux Konqueror", "Linux Mozilla", "Mac Firefox", "Mac Mozilla", "Mac Safari 4", "Mac Safari", "Windows Chrome", "Windows IE 6", "Windows IE 7", "Windows IE 8", "Windows IE 9", "Windows Mozilla", "iPhone", "iPad", "Android", "Mac FireFox", "Linux FireFox"] ,这与@Fab 略有不同
    • OP 的问题是“...以及如何解决”。 @severin 回答了如何解决它。不过,为解释点赞。
    【解决方案2】:

    实际上可以设置任何用户代理字符串:您必须使用方法Mechanize::Agent#user_agent= 而不是Mechanize::Agent#user_agent_alias=

    因此,如果您将示例更改为:

    m = Mechanize.new
    m.user_agent = 'My Custom User Agent'
    page = m.get("http://whatsmyuseragent.com/")
    

    然后就可以了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-01
      • 1970-01-01
      相关资源
      最近更新 更多