NoMethodError:ruby gem mechanize undefined method'q ='

时间:2013-06-09 23:40:51

标签: ruby web-scraping mechanize

我正在尝试为亚马逊构建一个网络编写程序,但我在第一步就被绊倒了。我编写了这样的代码,开始浏览并访问亚马逊和漂亮页面,所以我知道如何继续:

require 'rubygems'
require 'mechanize'

agent = Mechanize.new

page = agent.get('http://www.amazon.com/')

page_form = page.form('site-search')

page_form.q = 'Intermediate Microeconomics'

page = agent.submit(page_form, page_form.buttons.first)

pp page

我不断收到此错误消息:

/Users/samsunknight/.rvm/gems/ruby-2.0.0-p195/gems/mechanize-2.7.1/lib/mechanize/form.rb:217:in `method_missing': undefined method `q=' for #<Mechanize::Form:0x007f9a13012660> (NoMethodError)
        from webscraperattempt1.rb:7:in `<main>'

我已经从google.com的示例中调整了此代码,它可以无缝地适用于agent.get('www.google.com')page.form('f'),所以我想问题出在page.form('site-search'),但是当对于www.amazon.com,我pp page,“网站搜索”与Google的“f”完全相同。

我做错了什么? /我该如何解决?

3 个答案:

答案 0 :(得分:0)

试试这个

 page_form['q'] = 'Intermediate Microeconomics'

答案 1 :(得分:0)

q是Google表单上字段的名称。在亚马逊形式上它是另一回事。

答案 2 :(得分:0)

尝试使用'field-keywords'更改q,如下所示: page_form['field-keywords'] = 'Intermediate Microeconomics'