gpt4 book ai didi

ruby - 无方法错误 : undefined method `q=' for nil:NilClass: Mechanize; google scraping

转载 作者:行者123 更新时间:2023-12-04 16:19:41 24 4
gpt4 key购买 nike

我正在使用以下代码废弃谷歌

def google_search(query)
page = @agent.get('http://www.google.com')
google_form = page.form_with(:name => 'f')
google_form.q = query
page = @agent.submit(google_form)
page
end

但有时我会收到 NoMethodError: undefined method q=' 为 nil:NilClass` 错误。可能是什么问题?

最佳答案

您正在使用文档中的示例代码,在 google 搜索中没有该名称的表单,请尝试“gbqf”,但它可能因区域设置或各种设置而异。当您使用 Mechanize 时,请使用“pp”在开发过程中漂亮地打印元素,以查看您正在获取和下一步的内容。

工作 .rb 示例(从 http://mechanize.rubyforge.org/EXAMPLES_rdoc.html 更新)通过查询获得前 10 个结果。

require 'rubygems'
require 'mechanize'

a = Mechanize.new { |agent|
agent.user_agent_alias = 'Mac Safari'
}

a.get('http://google.com/') do |page|
search_result = page.form_with(:name => 'gbqf') do |search|
search.q = 'ruby mechanize'
end.submit

search_result.search(".//a[@class='l']").each_with_index.map do |link, i|
puts "#{i} #{link.content}"
end
end

关于ruby - 无方法错误 : undefined method `q=' for nil:NilClass: Mechanize; google scraping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10266781/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com