【问题标题】:Using Mechanize with Google Docs将机械化与 Google Docs 一起使用
【发布时间】:2010-06-08 20:51:39
【问题描述】:
我正在尝试使用 Mechanize 登录到 Google Docs,以便我可以抓取一些东西(无法从 API 中获取),但在尝试遵循元重定向时,我似乎一直收到 404:
require 'rubygems'
require 'mechanize'
USERNAME = "..."
PASSWORD = "..."
LOGIN_URL = "https://www.google.com/accounts/Login?hl=en&continue=http://docs.google.com/"
agent = Mechanize.new
login_page = agent.get(LOGIN_URL)
login_form = login_page.forms.first
login_form.Email = USERNAME
login_form.Passwd = PASSWORD
login_response_page = agent.submit(login_form)
redirect = login_response_page.meta[0].uri.to_s
puts "redirect: #{redirect}"
followed_page = agent.get(redirect) # throws a HTTPNotFound exception
pp followed_page
谁能明白为什么这不起作用?
【问题讨论】:
标签:
ruby
screen-scraping
mechanize
【解决方案1】:
安迪你太棒了!!
您的代码帮助我使我的脚本可行并登录到谷歌帐户。几个小时后我发现了你的错误。这是关于 html 转义的。正如我发现的那样,Mechanize 会自动转义它作为“get”方法的参数接收的 uri。所以我的解决方案是:
EMAIL = ".."
PASSWD = ".."
agent = Mechanize.new{ |a| a.log = Logger.new("mech.log")}
agent.user_agent_alias = 'Linux Mozilla'
agent.open_timeout = 3
agent.read_timeout = 4
agent.keep_alive = true
agent.redirect_ok = true
LOGIN_URL = "https://www.google.com/accounts/Login?hl=en"
login_page = agent.get(LOGIN_URL)
login_form = login_page.forms.first
login_form.Email = EMAIL
login_form.Passwd = PASSWD
login_response_page = agent.submit(login_form)
redirect = login_response_page.meta[0].uri.to_s
puts redirect.split('&')[0..-2].join('&') + "&continue=https://www.google.com/"
followed_page = agent.get(redirect.split('&')[0..-2].join('&') + "&continue=https://www.google.com/adplanner")
pp followed_page
这对我来说很好用。我已将元标记中的 continue 参数(已转义)替换为新参数。