【问题标题】:How to insert a string to a text field using mechanize in ruby?如何在 ruby​​ 中使用 mechanize 将字符串插入文本字段?
【发布时间】:2011-07-20 22:42:34
【问题描述】:

我知道这是一个非常简单的问题,但我被困了一个小时,我就是不明白这是怎么回事。

我需要从学校图书馆中抓取一些东西,因此我需要在文本字段中插入“CE”,然后单击带有文本“Clasificación”的链接。输出是我要用来工作的。所以这是我的代码。

require 'rubygems'
require 'open-uri'
require 'nokogiri'
require 'mechanize'

url = 'http://biblio02.eld.edu.mx/janium-bin/busqueda_rapida.pl?Id=20110720161008#'
searchStr = 'CE'

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

searchForm = page.form_with(:method => 'post')
searchForm['buscar'] = searchStr

clasificacionLink = page.link_with(:href => "javascript:onClick=set_index_and_submit(\'51\');").click
page = agent.submit(searchForm,clasificacionLink)

当我运行它时,它给了我这个错误

janium.rb:31: undefined method `[]=' for nil:NilClass (NoMethodError)

谢谢!

【问题讨论】:

    标签: ruby screen-scraping nokogiri mechanize nomethoderror


    【解决方案1】:

    我认为您的问题实际上是在第 13 行,而不是第 31 行,我什至会说明我为什么这么认为。您的脚本不仅没有 31 行,而且来自 fine manual:

    form_with(条件)
    查找单个表单匹配条件。

    该页面上有多个带有method="post" 的表单。显然,当 Mechanize 不能完全匹配 form_with 标准(包括文档中提到的 single 部分)时,它会返回 nil;因此,如果您的 criteria 匹配多个事物,form_with 会返回 nil 而不是选择其中一个选项,而您最终会尝试这样做:

    nil['buscar'] = searchStr
    

    但是nil 没有[]= 方法,所以你得到你的NoMethodError

    如果你使用这个:

    searchForm = page.form_with(:name => 'forma')
    

    您将通过第一部分,因为该页面上只有一个带有name="forma" 的表单。然后你会遇到麻烦:

    clasificacionLink = page.link_with(:href => "javascript:onClick=set_index_and_submit(\'51\');").click
    page = agent.submit(searchForm, clasificacionLink)
    

    因为 Mechanize 不知道如何处理 JavaScript(至少我的不知道)。但如果你只使用这个:

    page = agent.submit(searchForm)
    

    您将获得page,然后您可以继续构建和调试您的脚本。

    【讨论】:

      【解决方案2】:

      mu 的回答听起来很有道理。我不确定这是否是绝对必要的,但您也可以尝试在 searchStr 周围加上大括号。

      searchForm['buscar'] = [searchStr]
      

      【讨论】:

        猜你喜欢
        • 2015-07-26
        • 2018-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-12
        • 2021-02-26
        • 2020-08-31
        相关资源
        最近更新 更多