【问题标题】:Ruby Mechanize Clicking Not WorkingRuby机械化点击不起作用
【发布时间】:2016-12-23 09:55:59
【问题描述】:

这是我现在的代码的抓取部分

while counter <= 3
  url = "http://www.indeed.ca/jobs?q=" << job_title_search << "&l=" << job_location << ",+ON&start=" << (counter * 20).to_s
  counter += 1
  doc = Nokogiri::HTML(open(url))

  # can't put in if loop to only perform once for some reason
  page = agent.get(url)

  current_page = agent.page.uri
  puts current_page

  doc.css(".result").each do |item|
    job_title = item.at_css(".jobtitle").text[/[^\s][a-zA-Z -]*/]
    job_company = item.at_css(".company").text[/[^\s][a-zA-Z -]*/]
    full_job = job_title + " - " + job_company

    agent.current_page.link_with(:class => '.jobtitle').click
    posting_page = agent.page.uri
    puts posting_page

    if cache.include?(full_job) == false
      cache << full_job
      puts "#{job_title} - #{job_company}"
    end
  end

  puts ""
end

我知道存在“.jobtitle”类这一事实,因为返回职位标题的部分工作正常。我想弄清楚的是为什么 Mechanize 不允许我使用“点击”功能。在我在维基百科主页上进行的其他测试中,它在 CSS ID、类和文本上运行良好。

所以我的问题是是什么导致它在点击功能上失败?它生成的错误是通用的“nil:NilClass 的未定义方法 'click'”。

【问题讨论】:

    标签: ruby web-scraping automation nokogiri mechanize


    【解决方案1】:

    错误消息告诉我们,您正在调用click 方法的对象是nil。您在这里拨打click

    agent.current_page.link_with(:class => '.jobtitle').click
    

    ...所以我们可以推断您对link_with 的调用正在返回nil

    我认为这是失败的,因为您的页面没有class 属性等于.jobtitle 的链接。相反,您的页面可能有一个链接,其class 属性等于jobtitle。所以:

    agent.current_page.link_with(:class => 'jobtitle').click
    

    【讨论】:

    • 一开始我也是这么想的,但事实并非如此(只是再次尝试以确保我不会发疯),因为我在脚本的前面访问了“.jobtitle”类。
    • '.jobtitle' 是 css 选择器,'jobtitle' 是类(或其中的一部分)。
    猜你喜欢
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-02
    • 2010-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多