-
-
Save fongfan999/91b895877b92ae311f3941c1463cb22a to your computer and use it in GitHub Desktop.
Serialize authenticated Mechanize sessions in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AuthenticatedScraper | |
def initialize(args) | |
if args[:session] | |
@cookie_jar = args[:session] | |
@agent = Mechanize.new | |
@agent.cookie_jar = load_session(@cookie_jar) | |
else | |
@agent = Mechanize.new | |
@agent.login(args[:username], args[ password]) | |
end | |
@page = agent.get(initial_page) | |
@page_source = @page.parser.xpath("//html").to_html.to_s | |
@login_status = check_session_status | |
end | |
def load_session(cookie_jar) | |
@agent.cookie_jar = YAML::load(cookie_jar) | |
end | |
def save_session | |
@agent.cookie_jar.to_yaml | |
end | |
end | |
# Initial instantiation | |
if user.settings(:browser).session.nil? | |
obj = AuthenticatedScraper.new(username: "user", password: "pass") | |
serialized_session = obj.save_session | |
user.settings(:browser).session = serialized_session | |
end | |
obj.get(page) | |
# Subsequent instantiations | |
serialized_sesion = user.settings(:browser).session | |
obj = AuthenticatedScraper.new(sesion: serialized_sesion) | |
obj.get(page) | |
user.settings(:browser).session = obj.save_session |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment