ruby - Using random key/value from YAML file -
i'm trying use random key, value pair yaml file looks this:
'user_agents': 'mozilla': '5.0 (compatible; googlebot/2.1; +http://www.google.com/bot.html)' 'mozilla': '5.0 (compatible; yahoo! slurp; http://help.yahoo.com/help/us/ysearch/slurp)' 'mozilla': '5.0 (iphone; u; cpu iphone os 3_0 mac os x; en-us) applewebkit/528.18 (khtml, gecko) version/4.0 mobile/7a341 safari/528.16' 'mozilla': '4.0 (compatible; msie 6.0; windows nt 5.1)'
using script:
require 'mechanize' require 'yaml' info = yaml.load_file('test-rand.yml') @user_agent = info['user_agents'][info.keys.sample] agent = mechanize.new agent.user_agent = @user_agent if @user_agent.nil? puts "the user agent nil" else puts "using: #{@user_agent}" end
however while running script keep getting the user agent nil
, how pull random key/value yaml file?
i've tried @user_agent = info['user_agents'][info[rand(values.size)]]
i think figured out solution this, if has better 1 please let me know, changed yaml file have 1 mozilla
multiple values:
yaml:
'user_agents': 'mozilla': ['5.0 (compatible; googlebot/2.1; +http://www.google.com/bot.html)', '4.0 (compatible; msie 6.0; windows nt 5.1)', '5.0 (iphone; u; cpu iphone os 3_0 mac os x; en-us) applewebkit/528.18 (khtml, gecko) version/4.0 mobile/7a341 safari/528.16', '5.0 (compatible; yahoo! slurp; http://help.yahoo.com/help/us/ysearch/slurp)']
i took keys , value , broke down yaml file key value pair using this:
info = yaml.load_file('test-rand.yml') info['user_agents'].each |k,v|
from there turned value array, sampled array, , saved result variable, created new hash called @user_agent
, gave key of k
, value of arr_val.to_s
:
arr_val = v.to_a.sample @user_agent = {k => arr_val.to_s}
full script:
require 'mechanize' require 'yaml' info = yaml.load_file('test-rand.yml') info['user_agents'].each |k,v| arr_val = v.to_a.sample @user_agent = {k => arr_val.to_s} end agent = mechanize.new agent.user_agent = @user_agent if @user_agent.nil? puts "the user agent nil" else puts "using: #{@user_agent}" end #<= using: {"mozilla"=>"5.0 (iphone; u; cpu iphone os 3_0 mac os x; en-us) applewebkit/528.18 (khtml, gecko) version/4.0 mobile/7a341 safari/528.16"} #<= using: {"mozilla"=>"5.0 (compatible; googlebot/2.1; +http://www.google.com/bot.html)"} #<= using: {"mozilla"=>"4.0 (compatible; msie 6.0; windows nt 5.1)"}
Comments
Post a Comment