File Upload using Selenium Webdriver and ruby with < button type="button"> - html

I am using Selenium WebDriver and Ruby and I need to automate the file upload feature.
I tried with
WAIT.until { driver.find_element(:css,'div.ui-dialog-buttonset').displayed? }
by using this it gives time out error
elem = driver.find_element(:css,'div.ui-dialog-buttonset')
puts "Hi"
js = <<-end
var buttons = document.querySelectorAll('button');
buttons[0].setAttribute('aria-disabled', true);
end
elem = driver.execute_script(js, elem)
puts elem
elem.send_keys("C:\\Users\\seema\\Desktop\\1413.jpg")
Above code is not working and script fails by following error
here is HTML code
<div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix">
<div class="ui-dialog-buttonset">
<button class="otherButtonClass ui-state-hover ui-state-focus" type="button" role="button" aria-disabled="false">
<button class="otherButtonClass" type="button" role="button" aria-disabled="false" style="display: none;">
<button class="cancelButtonClass" type="button" role="button" aria-disabled="false">
</div>
</div>
here is error stack
,"message":"error - undefined me
thod `send_keys' for nil:NilClass \n [\"tests/upload_branding.rb:38:in `create_publish_pla
yer'\", \"tests/upload_branding.rb:80:in `PublishPlayerTest'\", \"org/jruby/RubyBasicObjec
t.java:1703:in `__send__'\", \"c:/jruby-1.7.4/lib/ruby/gems/shared/gems/minitest-4.7.4/lib
/minitest/unit.rb:1258:in `run'\", \"c:/jruby-1.7.4/lib/ruby/gems/shared/gems/minitest-rep
orters-0.14.20/lib/minitest/reporters.rb:62:in `run_with_hooks'\", \"c:/jruby-1.7.4/lib/ru
by/gems/shared/gems/scope-0.2.4/lib/scope.rb:105:in `run'\", \"org/jruby/RubyProc.java:255
:in `call'\", \"c:/jruby-1.7.4/lib/ruby/gems/shared/gems/scope-0.2.4/lib/scope.rb:153:in `
recursively_run_setup_and_teardown'\", \"c:/jruby-1.7.4/lib/ruby/gems/shared/gems/scope-0.
2.4/lib/scope.rb:155:in `recursively_run_setup_and_teardown'\", \"c:/jruby-1.7.4/lib/ruby/
gems/shared/gems/scope-0.2.4/lib/scope.rb:139:in `run_setup_and_teardown'\", \"c:/jruby-1.
7.4/lib/ruby/gems/shared/gems/scope-0.2.4/lib/scope.rb:105:in `run'\", \"c:/jruby-1.7.4/li
b/ruby/gems/shared/gems/minitest-4.7.4/lib/minitest/unit.rb:933:in `_run_suite'\", \"org/j
ruby/RubyArray.java:2417:in `map'\", \"c:/jruby-1.7.4/lib/ruby/gems/shared/gems/minitest-4
.7.4/lib/minitest/unit.rb:926:in `_run_suite'\", \"c:/jruby-1.7.4/lib/ruby/gems/shared/gem
s/minitest-reporters-0.14.20/lib/minitest/reporter_runner.rb:45:in `_run_suite'\", \"c:/jr
uby-1.7.4/lib/ruby/gems/shared/gems/minitest-4.7.4/lib/minitest/parallel_each.rb:71:in `_r
un_suites'\", \"org/jruby/RubyArray.java:2417:in `map'\", \"c:/jruby-1.7.4/lib/ruby/gems/s
hared/gems/minitest-4.7.4/lib/minitest/parallel_each.rb:70:in `_run_suites'\", \"c:/jruby-
1.7.4/lib/ruby/gems/shared/gems/minitest-reporters-0.14.20/lib/minitest/reporter_runner.rb
:37:in `_run_suites'\", \"c:/jruby-1.7.4/lib/ruby/gems/shared/gems/minitest-4.7.4/lib/mini
test/unit.rb:877:in `_run_anything'\", \"c:/jruby-1.7.4/lib/ruby/gems/shared/gems/minitest
-4.7.4/lib/minitest/unit.rb:1085:in `run_tests'\", \"c:/jruby-1.7.4/lib/ruby/gems/shared/g
ems/minitest-reporters-0.14.20/lib/minitest/reporter_runner.rb:30:in `run_tests'\", \"org/
jruby/RubyBasicObject.java:1703:in `__send__'\", \"org/jruby/RubyKernel.java:2209:in `send
'\", \"c:/jruby-1.7.4/lib/ruby/gems/shared/gems/minitest-4.7.4/lib/minitest/unit.rb:1072:i
n `_run'\", \"org/jruby/RubyArray.java:1617:in `each'\", \"c:/jruby-1.7.4/lib/ruby/gems/sh
ared/gems/minitest-4.7.4/lib/minitest/unit.rb:1071:in `_run'\", \"c:/jruby-1.7.4/lib/ruby/
gems/shared/gems/minitest-4.7.4/lib/minitest/unit.rb:1059:in `run'\", \"tests/upload_brand
ing.rb:87:in `(root)'\"]","result":false}
In IRB i found following errors
irb(main):038:0> Wait.until { $driver.find_element(:css,'div.ui-dialog-buttonse>button')[1].displayed? }
Selenium::WebDriver::Error::TimeOutError: timed out after 80 seconds (Unable to locate element: {"method":"css selector","selector":"div.ui-dialog-buttonse>button"})}
from C:/jruby-1.7.4/lib/ruby/gems/shared/gems/selenium-webdriver-2.33.0/lib/selenium/webdriver/common/wait.rb:57:in `until'
from (irb):38:in `evaluate'
from org/jruby/RubyKernel.java:1093:in `eval'
from org/jruby/RubyKernel.java:1489:in `loop'
from org/jruby/RubyKernel.java:1254:in `catch'
from org/jruby/RubyKernel.java:1254:in `catch'
from C:\jruby-1.7.4\/bin/jirb_swing:53:in `(root)'
also for second command
irb(main):043:0> elem = $driver.find_element(:css,'div.ui-dialog-buttonse>button')[1]
Selenium::WebDriver::Error::NoSuchElementError: Unable to locate element: {"method":"css selector","selector":"div.ui-dialog-buttonse>button"}
from [remote server] file:///C:/Users/seema/AppData/Local/Temp/webdriver-profile20130704-2984-1wifg7r/extensions/fxdriver#googlecode.com/components/driver_component.js:8444:in `FirefoxDriver.prototype.findElementInternal_'
from [remote server] file:///C:/Users/seema/AppData/Local/Temp/webdriver-profile20130704-2984-1wifg7r/extensions/fxdriver#googlecode.com/components/driver_component.js:8453:in `FirefoxDriver.prototype.findElement'
from [remote server] file:///C:/Users/seema/AppData/Local/Temp/webdriver-profile20130704-2984-1wifg7r/extensions/fxdriver#googlecode.com/components/command_processor.js:10456:in `DelayedCommand.prototype.executeInternal_/h'
from [remote server] file:///C:/Users/seema/AppData/Local/Temp/webdriver-profile20130704-2984-1wifg7r/extensions/fxdriver#googlecode.com/components/command_processor.js:10461:in `DelayedCommand.prototype.executeInternal_'
from [remote server] file:///C:/Users/seema/AppData/Local/Temp/webdriver-profile20130704-2984-1wifg7r/extensions/fxdriver#googlecode.com/components/command_processor.js:10401:in `DelayedCommand.prototype.execute/<'
from C:/jruby-1.7.4/lib/ruby/gems/shared/gems/selenium-webdriver-2.33.0/lib/selenium/webdriver/remote/response.rb:51:in `assert_ok'
from C:/jruby-1.7.4/lib/ruby/gems/shared/gems/selenium-webdriver-2.33.0/lib/selenium/webdriver/remote/response.rb:15:in `initialize'
from C:/jruby-1.7.4/lib/ruby/gems/shared/gems/selenium-webdriver-2.33.0/lib/selenium/webdriver/remote/http/common.rb:59:in `create_response'
from C:/jruby-1.7.4/lib/ruby/gems/shared/gems/selenium-webdriver-2.33.0/lib/selenium/webdriver/remote/http/default.rb:66:in `request'
from C:/jruby-1.7.4/lib/ruby/gems/shared/gems/selenium-webdriver-2.33.0/lib/selenium/webdriver/remote/http/common.rb:40:in `call'
from C:/jruby-1.7.4/lib/ruby/gems/shared/gems/selenium-webdriver-2.33.0/lib/selenium/webdriver/remote/bridge.rb:629:in `raw_execute'
from C:/jruby-1.7.4/lib/ruby/gems/shared/gems/selenium-webdriver-2.33.0/lib/selenium/webdriver/remote/bridge.rb:607:in `execute'
from C:/jruby-1.7.4/lib/ruby/gems/shared/gems/selenium-webdriver-2.33.0/lib/selenium/webdriver/remote/bridge.rb:575:in `find_element_by'
from C:/jruby-1.7.4/lib/ruby/gems/shared/gems/selenium-webdriver-2.33.0/lib/selenium/webdriver/common/search_context.rb:42:in `find_element'
from (irb):43:in `evaluate'
from C:\jruby-1.7.4\/bin/jirb_swing:53:in `(root)'
Kindly help

First check out the link Selenium::WebDriver::Wait to avoid such time out error.
You can try the below code :
# implicit time out declarations
wait = Selenium::WebDriver::Wait.new(:timeout => 60)
# wait till the required button element being displayed
# Use the link : http://www.w3schools.com/cssref/css_selectors.asp
# for css selectors
wait.until { driver.find_element(:css,'div.ui-dialog-buttonse>button')[1].displayed? }
elem = driver.find_element(:css,'div.ui-dialog-buttonse>button')[1]
elem.sendKeys("C://path/To/File.jpg")
Update
Looking at the link aria-disabled attribute and your part html below, I am seeing aria-disabled is set as false :
<button class="otherButtonClass ui-state-hover ui-state-focus" type="button" role="button" aria-disabled="false">
That desired button element is disabled.
Now see the question : Does WebDriver support file uploads?
You can't interact with the native OS file browser dialog directly, but we do some magic so that if you call WebElement#sendKeys("/path/to/file") on a file upload element, it does the right thing. Make sure you don't WebElement#click() the file upload element, or the browser will probably hang.
Update
#implicit time out declarations
wait = Selenium::WebDriver::Wait.new(:timeout => 60)
#wait till the div element is being displayed
wait.until { driver.find_element(:css,'div.ui-dialog-buttonse').displayed? }
elem = driver.find_element(:css,'div.ui-dialog-buttonse')
js = <<-end
var buttons = document.querySelectorAll('button');
buttons[0].setAttribute('aria-disabled', true);
end
elem = driver.execute_script(js, elem)
elem.sendKeys("C://path//To//File.jpg")

Related

python selenium find button to click

The html context is like:
<div role="button" class="quantumWizButtonEl quantumWizButtonPaperbuttonEl quantumWizButtonPaperbuttonFlat quantumWizButtonPaperbuttonFlatColored quantumWizButtonPaperbutton2El2 quantumWizDialogPaperdialogDialogButton exportDefaultDialogButton freebirdThemedFlatButton isUndragged" jscontroller="VXdfxd" jsaction="click:cOuCgd; mousedown:UX7yZ; mouseup:lbsD7e; mouseenter:tfO1Yc; mouseleave:JywGue; focus:AHmuwe; blur:O22p3e; contextmenu:mg9Pef;touchstart:p6p2H; touchmove:FwuNnf; touchend:yfqBxc(preventMouseEvents=true|preventDefault=true); touchcancel:JMtRjd;" jsshadow="" jsname="LgbsSe" aria-disabled="false" tabindex="0" data-id="EBS5u" autofocus=""><div class="quantumWizButtonPaperbuttonRipple exportInk" jsname="ksKsZd"></div><div class="quantumWizButtonPaperbuttonFocusOverlay exportOverlay"></div><span jsslot="" class="quantumWizButtonPaperbuttonContent"><span class="quantumWizButtonPaperbuttonLabel exportLabel">登录</span></span></div>
The complete html code is here
I want to click the button named 登录 by
driver.find_element_by_link_text("登录").click()
The error is:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"link text","selector":"登录"}

Clicking on web-table with selenium python 3

<tr id="GBPUSD" class="filled" title="Great Britain Pound vs US Dollar
Calculation: Forex
Trade: Full access" draggable="true" style="background: rgb(255, 255, 255);"><td
id="symbol" class="symbol"><div class="container"><span class="content">
<span class="i down"> </span>GBPUSD</span></div></td>
<td id="bid" class="down" style="text-align: right;">
<div class="container"><span class="content">1.28106</span></div></td>
<td id="ask" class="down" style="text-align: right;"><div class="container">
<span class="content">1.28116</span></div></td><td></td></tr>
This is the html code for the item that i want to doubleclick on with selenium webdriver.
elem = driver.find_element_by_xpath("//tr[#id='GBPUSD']")
elem.click()
elem.click()
This is my python code, but I keep getting an error:
selenium.common.exceptions.InvalidSelectorException: Message: invalid selector:
Unable to locate an element with the xpath expression //*[#id='symbol']/div]
because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//*[#id='symbol']/div]' is not a valid XPath expression.
(Session info: chrome=78.0.3904.87)
Please help me :(
Your code is showing one XPath, but your error message is showing another one -- the XPath in your error message is wrong (//*[#id='symbol']/div]) and should be changed to //*[#id='symbol']/div
The code in your sample is not actually the code that's throwing the error here.
Also, you can double click properly like this:
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
// wait for element to exist
elem = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, "//tr[contains(#title, 'Great Britain Pound')]")))
// double click the element
actionChains = ActionChains(driver)
actionChains.double_click(elem).perform()

Checkbox checked flask

I have a problem with a checkbox in a form
<form id="form" action="/findPkgInstalled" role="form" method = "POST">
<div class="input-group col-xs-4">
<input type="text" name="pkgSearch" placeholder="Ricerca applicazione non installate..">
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
<h6><input type="checkbox" name="filterName" checked>Filtra per nome</h6>
</form>
while in Python I have:
#app.route('/findPkgInstalled', methods=['POST'])
def findPkgInstalled():
error = None
pkg = request.form['pkgSearch']
if not pkg:
flash(u'Operazione errata, impossibile ricercare stringa vuota','warning')
return redirect(url_for('listInstalled'))
else:
if request.form['filterName'] is 'on':
appFound = aptsearch(pkg,True)
return render_template('find-pkg-not-installed.html', appFound = appFound)
else:
appFound = aptsearch(pkg,False)
return render_template('find-pkg-not-installed.html', appFound = appFound)
return redirect(url_for('listInstalled'))
box = request.form['filterName']
but this does not work. The error reported is 400 Bad Request. How can I do? Can you help me, please?
This error means that you're trying to fetch an object from your post request using incorrect key. For example if you uncheck filterName checkbox - this will cause this error:
request.form['filterName']
My advises:
0) Always check your post body to know what keys you can use to retrieve values from this body.
1) Use
request.form.get('filterName')
instead of
request.form['filterName']
because .get() returns None is there is no such key instead of throwing an exception inside flask that leads to 400 error
2) Use
request.form.get('filterName') == 'on'
instead of
request.form['filterName'] is 'on'
because is returns True if two variables point to the same object in memory. I'm not sure if you already have 'on' object in process memory

should I turn off Smarty debug option?

I use Codeigniter and Smarty template engine.
I did a form validation using Codeigniter's form validation library. So if user inputs some data I need to have a method to verify it.
If form passes validation no errors should be displayed in the view.
If form doesn't pass validation the I use this line of code: $this->data['error_message'] = $this->form_validation->error_array();
To store which errors occured.
So, in my template I did this:
<div id="cl-wrapper" class="login-container">
<div class="middle-login">
{if $error_message != ""}
<div class="alert alert-danger">
{foreach from=$error_message item=curr_id}
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<i class="fa fa-times-circle sign"></i><strong>Error!</strong> {$curr_id}<br/>
{/foreach}
</div>
{/if}
<div class="block-flat">
//some code
</div>
</div>
</div>
The thing is that if form validates OK, a smarty template error is thrown:
Message: Undefined index: error_message
Filename: sysplugins/smarty_internal_templatebase.php(151) : eval()'d code
Line Number: 65
I would like to know why, because I'm previosly asking if $error_message has something inside...
This didn't happened to me before...in another project.
Thanks in advance.
J.
EDIT 13/05/2014
I found a post here with same question. It says debugging should be off. I checked on Smarty.class.php and variable $debugging = false. So now I'm really lost...
Check your controller if there is $data['error_message'].
Also you could do this if state with only ! or just check value.
{if $error_message}{/if}
It seems that Smarty doesn't know what $error_message is so the problem is not foreach loop but this comparison {if $error_message != ""} Remove foreach loop and check again.
You should check the place where you make assignment in PHP.
It should be something like this (I don't know codeigniter):
$smarty->assign('error_message', $this->data['error_message']);
Maybe the problem is that you should in Smarty use not $error_message but for example $data.error_message?
If you want to turn off Smarty errors, you should use muteExpectedErrors() function as described here - http://www.smarty.net/docs/en/api.mute.expected.errors.tpl - it's from 3.1.2 version. Before you should use error_reporting - http://www.smarty.net/docs/en/variable.error.reporting.tpl to set desired level to Smarty object

Watir and Cucumber. link not clickable

I am new to Watir and Cucumber, and I am trying to run an automation to create Live IDs. Below is the HTML for the link that I want to click, the "New" text is what it is showing on webpage. It would lead me to the form to add new contact to my Live account.
<ul class="c_cc" role="presentation" styple="overflow:visible;">
<li class="c_sm c_mcp" id = "new">
<a id href="#" class="c_nobdr t_prs">
<span class="is_c" dir="ltr" style="padding-right: 5px;">
<img class="is_img" src="https://p.pfx.ms/is/invis.gif" onload="this.onload=null;$Do.when('$IS.Init',0,this);" style="width:26px;height:26px;background-position:-1px -1px;background-image:url('https://p.pfx.ms/h/command4.png');" alt="New contact" title />
</span>
"New"
</a>
<span class="c_ms"></span>
</li>
</ul>
the watir code I wrote to click the "New" is below:
#browser.div(:id, "c_header").div(:id, "c_cb0").ul(:class, "c_cc").span(:text, "is_c").when_present.click
I get this error:
Watir::Wait::TimeoutError: timed out after 30 seconds, waiting for {:id=>"is_c", :tag_name=>"span"} to become present
Then I tried below code:
#browser.div(:id, "c_header").div(:id, "c_cb0").ul(:class, "c_cc").span(:text, "New").when_present.click
but this code does not really clicking on the "New" link, so the next form won't show up, and the rest of the code cannot run. Does anyone know any solution to this problem?
I found out a new window popped up, so it could not find the element in the old window. Thanks guys for helping.
In the first watir code snippet, a :text locator is being used for the .span method instead of a :class locator. For example:
browser.ul(:class, "c_cc").span(:text, "is_c").exists? #=> false
browser.ul(:class, "c_cc").span(:class, "is_c").exists? #=> true
In the second watir code snippet, a :text locator with a value of "New" is being used for the .span method. In this case, a .link method should be used. Additionally, the string includes double-quotes, so the double-quotes must be escaped if enclosed in another set of double-quotes (or enclose in single-quotes). For example:
browser.ul(:class, "c_cc").span(:text, "New").exists? #=> false
browser.ul(:class, "c_cc").span(:text, "\"New\"").exists? #=> false
browser.ul(:class, "c_cc").link(:text, "\"New\"").exists? #=> true
browser.ul(:class, "c_cc").link(:text, '"New"').exists? #=> true
So, one of the following examples should work:
browser.link(:text, "\"New\"").when_present.click
browser.link(:text, '"New"').when_present.click
browser.link(:class, "c_nobdr t_prs").when_present.click
Wow. This is old and I have encountered the same behavior. First, this is in a Cucumber step definition. The following works perfectly in open Ruby code. It simply refuses to function as a step.
It finds the link in the table and clicks it. Click doesn't function.
link = browser.table(class: 'alert-table').tbody.rows[1].cells.last.link(text: 'View')
# <Watir::Anchor: located: false; {:class=>"alert-table", :tag_name=>"table"} --> {:tag_name=>"tbody"} --> {:index=>1} --> {:index=>-1} --> {:text=>"View", :tag_name=>"a"}>
link.click
Ruby 2.4
watir (6.16.5)
regexp_parser (~> 1.2)
selenium-webdriver (~> 3.6)