Fedex Ruby Mechanize: Unable to log in - ruby

I'm trying to automate my fedex processing via Ruby gem Mechanize.
I've set up the initial script similar to what has worked for me on the Amazon Seller Central page. However, I seem to be unable to fully log in to the fedex website and I appear to just be "staying" on the login page.
If you have any idea what my code is missing, it would be appreciated!
CODE
Dir.chdir 'C:\Ruby22\bin'
require "rubygems"
require "mechanize"
require "certified"
require "logger"
#Initialize and set agent settings:
agent = Mechanize.new
agent.user_agent_alias = 'Windows Chrome'
agent.follow_meta_refresh = true
agent.redirect_ok = true
#Log in to fedex
login_url = "https://www.fedex.com/dk/"
page_login = agent.get(login_url)
puts "Login Page: " + page_login.title.to_s
form = page_login.form_with(:name => "logonForm")
#form.fields.each { |f| puts f.name }
form.username = "************"
form['ap_signin_existing_radio'] = "1"
form.password = "*********"
agent.submit(form)
page_home = agent.get(login_url)
puts "Fedex Dashboard Page: " + page_home.title

Related

Watir won't download PDF, only opens in viewer

I was trying to test with Selenium, but can not download a pdf, pdfs keep opening.
See my other post: RUBY: Selenium webdriver, setup to download pdf files instead of opening them
It was advised to try Watir, so I did, and I get the same result. Here is my Watir setup. Please advise on how to fix this issue.
require 'watir'
require 'pry'
prefs = {
download: {
prompt_for_download: false,
default_directory: '/Users/ar/pdf_downloads'
}
}
browser = Watir::Browser.new :chrome, options: {prefs: prefs}
# Goto Login Page (file)
url="file:///Users/ar/info.html"
browser.goto url
browser.button(id: 'formsubmit').click
sleep 5
# Goto info
info_url = 'https://webapp.domain.com/info'
browser.goto info_url
sleep 5
elements = browser.elements(css: "#ar-pdfreport a")
link = elements.first.attribute("href")
browser.goto link
There is a bug in Selenium-WebDriver v3.142.7 where using symbols for the prefs generates the wrong result - eg does not set the download directory. See https://github.com/SeleniumHQ/selenium/issues/7917 for more details.
Switch the symbols to Strings:
prefs = {
download: {
'prompt_for_download' => false,
'default_directory' => '/Users/ar/pdf_downloads'
},
plugins: {
'always_open_pdf_externally' => true
}
}

How to register Firefox driver with the customized profile to run with Capybara?

I tried to register selenium driver for Firefox through the below snippet. Actually i wanna set the customized user agent, but looks like after launching the browser, the user agent was not as I expected . Could anyone take a look at if there's something wrong? Thanks a lot
I'm running this with
* GeckoDriver 0.24
* Firefox ver 67.0
* Capybara 3.18.0
* Selenium WebDriver gem 3.142.3
Capybara.register_driver :selenium do |app|
browser = ENV['BROWSER']
browser_sym = browser.to_sym
options = {
browser: browser_sym,
}
if browser == :firefox
profile = Selenium::WebDriver::Firefox::Profile.new
profile['browser.download.folderList'] = 2
profile['browser.helperApps.neverAsk.saveToDisk'] = 'text/csv'
profile['dom.max_script_run_time'] = Configuration['browser']['wait_time']
profile['general.useragent.override'] = 'customized user-agent'
profile['dom.max_chrome_script_run_time'] = Configuration['browser']['wait_time']
profile['dom.max_script_run_time'] = Configuration['browser']['wait_time']
options[:profile] = profile
elsif browser == :chrome
.....
end
Capybara::Selenium::Driver.new(app, options)
Going to the launched browser and check the return result from Firefox Dev Console by command navigator.userAgent and it returns the default value not the customized user-agent.
To set the user agent in the Firefox profile your conditionals need to end up resolving to something like
Capybara.register_driver :ff do |app|
profile = Selenium::WebDriver::Firefox::Profile.new
profile['general.useragent.override'] = 'Random User Agent'
opts = Selenium::WebDriver::Firefox::Options.new(profile: profile)
Capybara::Selenium::Driver.new(app, browser: :firefox, options: opts)
end
You can run it yourself using the code at https://gist.github.com/twalpole/2f69984a5c6063aab04ea25c0aa3d2ca

Page Objects in Selenium with Ruby

I'm familiar with Page Objects in Watir-Webdriver using Ruby, but now i'm trying to define Page Objects in Selenium-Webdriver with Ruby and facing the below issue. Could any one please help.
require "selenium-webdriver"
require "page-object"
Firstname = {id: "firstname"}
#driver = Selenium::WebDriver.for :firefox
#driver.get ("http://www.practiceselenium.com/practice-form.html")
#driver.manage().window.maximize()
#driver.find_element(Firstname).send_keys "User1"
Unable to locate element: {"method":"id","selector":"firstname"} (Selenium::WebDriver::Error::NoSuchElementError)
There is no id: "firstname" attribute on the page you specified. Try name: "firstname" instead:
require "selenium-webdriver"
require "page-object"
Firstname = {name: "firstname"}
#driver = Selenium::WebDriver.for :firefox
#driver.get ("http://www.practiceselenium.com/practice-form.html")
#driver.manage().window.maximize()
#driver.find_element(Firstname).send_keys "User1"
Or in a more object oriented fashion:
require "selenium-webdriver"
require "page-object"
class PraticeForm
include PageObject
page_url "http://www.practiceselenium.com/practice-form.html"
text_field(:firstname, :name => 'firstname')
end
browser = Selenium::WebDriver.for :firefox
my_page_object = PraticeForm.new(browser)
my_page_object.goto
my_page_object.firstname = "User1"

How do I access the Magento REST API with Ruby?

I want to start working with Magento's REST API, but I can't seem to get it working.
To start with I need to get access tokens, here's what I'm trying:
require 'oauth'
#consumer = OAuth::Consumer.new("4200100753b2c8b03bde1f5b062c5a80", "c06abdcb734c85dfd7bb115c6a67ae4d", {:site=>"http://178.62.173.99/"})
#request_token = #consumer.get_request_token
# => oauth-0.4.7/lib/oauth/consumer.rb:216:in `token_request': 404 Not Found (OAuth::Unauthorized)
But I keep getting a 404 error.
What should I try next?
Here's a Ruby module I've written to create an access token for the Magento REST API:
module Token
def create_consumer
OAuth::Consumer.new(
CONSUMER_KEY,
CONSUMER_SECRET,
:request_token_path => '/oauth/initiate',
:authorize_path=>'/admin/oauth_authorize',
:access_token_path=>'/oauth/token',
:site => URL
)
end
def request_token(args = {})
args[:consumer].get_request_token(:oauth_callback => URL)
end
def get_authorize_url(args = {})
args[:request_token].authorize_url(:oauth_callback => URL)
end
def authorize_application(args = {})
m = Mechanize.new
m.get(args[:authorize_url]) do |login_page|
auth_page = login_page.form_with(:action => "#{URL}/index.php/admin/oauth_authorize/index/") do |form|
form.elements[1].value = ADMIN_USERNAME
form.elements[2].value = ADMIN_PASSWORD
end.submit
authorize_form = auth_page.forms[0]
#callback_page = authorize_form.submit
end
#callback_page.uri.to_s
end
def extract_oauth_verifier(args = {})
callback_page = "#{args[:callback_page]}".gsub!("#{URL}/?", '')
callback_page_query_string = CGI::parse(callback_page)
callback_page_query_string['oauth_verifier'][0]
end
def get_access_token(args = {})
args[:request_token].get_access_token(:oauth_verifier => args[:oauth_verifier])
end
def save_tokens_to_json(args = {})
auth = {}
auth[:time] = Time.now
auth[:token] = args[:access_token].token
auth[:secret] = args[:access_token].secret
File.open("#{args[:path]}#{args[:filename]}.json", 'w') {|f| f.write(auth.to_json)}
auth
end
def get_new_access_tokens
new_consumer = self.create_consumer
new_request_token = self.request_token(consumer: new_consumer)
new_authorize_url = self.get_authorize_url(request_token: new_request_token)
authorize_new_application = self.authorize_application(authorize_url: new_authorize_url)
extract_new_oauth_verifier = self.extract_oauth_verifier(callback_page: authorize_new_application)
new_access_token = self.get_access_token(request_token: new_request_token, oauth_verifier: extract_new_oauth_verifier)
save_tokens_to_json(filename: 'magento_oauth_access_tokens', path: '/', access_token: new_access_token)
return 'Successfully obtained new access tokens.'
end
end
Run #get_new_access_tokens to get an access token.
Don't forget to define the following variable:
CONSUMER_KEY
CONSUMER_SECRET
URL
ADMIN_USERNAME
ADMIN_PASSWORD
Check out mage on rails. It should work right out of the box. Check out this page for annotated ruby code showcasing the oauth flow

Ruby/Mechanize Multipart Form With File Upload to a Mediawiki

I've been trying to write a ruby script using mechanize to batch upload a large number of images to a MediaWiki. The script runs without any errors but I suspect there is something wrong with the way I'm handling multipart forms with mechanize. The result variable at the end of the code gives no indication of success or failure, it just shows the page with all of the values filled in, wpDestFile is DezzImage.png and so on like I specified. end.submit seems to do nothing.
Below is a the complete code for uploading a single file, a few variables need filling in for it to work.
require 'rubygems'
require 'mechanize'
require 'nokogiri'
loginName = ""
loginPassword = ""
wikiUploadPage = "http://en.wikipedia.org/wiki/Special:Upload"
wikiLoginPage = "http://en.wikipedia.org/wiki/Special:UserLogin"
pathToImage = "/home/milo/image.png"
agent = Mechanize.new {|agent| agent.user_agent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.4) Gecko/20100513 Firefox/3.6.4" }
agent.pre_connect_hooks << lambda { |params| params[:request]['Connection'] = 'keep-alive' }
agent.follow_meta_refresh = true
agent.get(wikiLoginPage) do |page|
login_result = page.form_with(:method => /POST/) do |form|
form.wpName = loginName
form.wpPassword = loginPassword
end.submit
end
uploadPage = agent.get(wikiUploadPage)
result = uploadPage.form_with(:method => /POST/) do |form|
form.file_uploads.first.file_name = pathToImage
form.wpDestFile = "DezzImage.png"
form.wpUploadDescription = "DezzImage.png"
end.submit
We solved this elsewhere, but the problem seemed to be a misconfiguration in the MediaWiki install. Setting:
form.checkbox_with(:name => "wpIgnoreWarning").check
with the form submission seems to have addressed the issue.
Looks like you're not actually setting the POST parameter that submits the page for uploading. Try something like this:
result = uploadPage.form_with(:method => /POST/) do |form|
form.file_uploads.first.file_name = pathToImage
form.wpDestFile = "DezzImage.png"
form.wpUploadDescription = "DezzImage.png"
form.wpUpload = True
end.submit
I have the same problem.
after viewed the source code, I found the solution:
result = uploadPage.form_with(:method => /POST/) do |form|
form.file_uploads.first.file_name = pathToImage
form.wpDestFile = "DezzImage.png"
form.wpUploadDescription = "DezzImage.png"
form.checkbox_with(:name => "wpIgnoreWarning").check
end.click_button

Resources