selenium,webdriver,mapping , Selenium Web Driver : How to map html elements to Java Object.


Selenium Web Driver : How to map html elements to Java Object.

Question:

Tag: selenium,webdriver,mapping

As part of Selenium Web-driver learning I came across a scenario. Please let me know the professional approach to proceed.

I am testing a eCommerce application where while I click on Mobile link all mobile phones are getting displayed.I want to check whether they are sorted based on name and price. So basically I need to get Name & price of all elements in the result page.

So My Question is there any way I can map html elements to java value objects ? Any API already available for doing this mapping for me ? Something similar to gson api for converting java objects to their corresponding Json representation ?

Deepu Nair


Answer:
//Get all the mobile phones links into a list before sorting

 List<WebElement> mobilelinks=driver.findElements(("locator"));

 Map maps = new LinkedHashMap();//use linked hash map as it preserves the insertion order

 for(int i=0;i<mobilelinks.size();i++){

 //store the name and price as key value pair in map

 maps.put("mobilelinks.get(i).getAttribute('name')","mobilelinks.get(i).getAttribute('price')" );

    }

    /*sort the map based on keys(names) store it in a separate list
      sort the map based on values(prices) store it in a separate list
     */

    /* Using webdriver click the sort by name and compare it with the list which we got after sorting

     and also click sort by prices and compare it with the list*/

To catch an assertion and continue with the test after assertion failures override the Assertion class and create your own CustomAssertion or use SoftAssertions

CustomAssertion.java

public class CustomAssertions extends Assertion {

  private Map<AssertionError, IAssert> m_errors = Maps.newLinkedHashMap();

  @Override
  public void executeAssert(IAssert a) {
    try {
      a.doAssert();
    } catch(AssertionError ex) {
      onAssertFailure(a, ex);
      System.out.println(a.getActual());
      System.out.println(ex.getMessage());
      m_errors.put(ex, a);
    }
  }

  public void assertAll() {
    if (! m_errors.isEmpty()) {
      StringBuilder sb = new StringBuilder("The following asserts failed:\n");
      boolean first = true;
      for (Map.Entry<AssertionError, IAssert> ae : m_errors.entrySet()) {
        if (first) {
          first = false;
        } else {
          sb.append(", ");
        }
        sb.append(ae.getKey().getMessage());
      }
      throw new AssertionError(sb.toString());
    }
  }
}

Instead of using Assertions class to verify the tests use CustomAssertions class

Ex:

//create an object of CustomAssertions class

CustomAssertions custom_assert=new CustomAssertions();

cust_assert.assertTrue(2<1);

cust_assert.assertEquals("test", "testing");

//and finally after finishing the test in aftersuite method call

cust_assert.assertAll();

Hope this helps you if you have any doubts kindly get back...


Related:


Checking element existence on the page with WebDriver findElements().isEmpty method


java,selenium,selenium-webdriver
I wish to check if some element exists on the page or not. I already saw this WebDriver: check if an element exists? issue but I'm wondering why not simply apply findElements().isEmpty method? I thought it would do the same work. UPD Now I see findElements().isEmpty works perfect so I'm...

CSS Selector-How to locate Parent Element


selenium,selenium-webdriver,css-selectors,webdriver
Is there any way to locate parent element in CSS Selector? i am using below code but i am not getting the parent element. WebElement we=dr.findElement(By.cssSelector("div[id='gf-BIG']:parent")); I know there is a way in Xapth but please let me know that how we can locate parent in CSS Selector. ...

Getting value from div which contains exact string using Selenium IDE


selenium,selenium-ide
I am trying to get a value from a nested div in a web page using Selenium IDE where class names are repeated but contain unique strings, such as the structure below, but am having no luck. <div class='ClassName'> <div class="col_Num">1 </div> <div class="col_Val">5.00 </div> </div> <div class='ClassName'> <div class="col_Num">2...

Webdriver C# -Click second linktext not first


c#,selenium,webdriver
By this line I click on the first text, but how can I click the second exact text? driver.FindElement(By.PartialLinkText("Play")).Click(); ...

Selecting elements by ng-model attribute with selenium-webdriver


ruby,angularjs,selenium,selenium-webdriver
I am using Ruby and the gem selenium-webdriver I am working with an angular form that I have no control over and would like to know how to find elements via their ng-model attributes. Here is an example select element: <select class="medium-3 small-12 columns ng-pristine ng-valid ng-touched" ng-model="ctrl.type" ng-options="type.name for...

Upload file - Protractor


javascript,selenium,testing,protractor,end-to-end
I fight with protractor because for some tests I need to UPLOAD file. My HTML looks like: <div class="panel-footer"> <ul class="list-unstyled"> <!-- ngRepeat: file in imagesToUpload --> </ul> <button class="btn btn-sm btn-success pull-right ng-binding ng-hide" ng-show="imagesToUpload.length" ng-click="uploadImages()">Nahrát na server</button> <button class="btn btn-sm btn-primary ng-binding" ng-file-select="onImageSelect($files)" data-multiple="true" style="overflow: hidden;">Vybrat soubory<input...

Selenium C# Element Not Found Taking a Long Time


c#,unit-testing,selenium,selenium-webdriver
I am using Selenium for C# to test a page. Is there a way to quickly fail if the element is not found on the page? I am experiencing if the HTML element is not found on the page the Selenium test a very long time and then eventually it...

XPath for child element


selenium,xpath
What is the Xpath to select the first element of this jquery selector: $('.A .B:eq(1)') ? HTML Sample <div class="x A z"> <div class="y"> <div class="r B z"></div> <---- that is that I need to select <div class="r B z"></div > ... So far I've tried this: (//div[(@class='A') and div[contains(concat('...

Selenium Web Driver : How to map html elements to Java Object.


selenium,webdriver,mapping
As part of Selenium Web-driver learning I came across a scenario. Please let me know the professional approach to proceed. I am testing a eCommerce application where while I click on Mobile link all mobile phones are getting displayed.I want to check whether they are sorted based on name and...

WebDriver can't get dropdown menu element (Java)


java,selenium,webdriver,junit4
I write a script on Java for Selenium WebDriver, and I have a problem with selected from dropdown menu. Here's my locator: new Select(driver.findElement(By.id("FormElement_select_68_input_input"))).selectByVisibleText("Image"); Here's an error: http://prntscr.com/7jul03 Here's HTML code: http://prntscr.com/7jvou6 Need to select "Image" from this menu, but have an error. Before I had the error like this,...

webdriver C# - click this element with XPath position?


c#,selenium,xpath,webdriver
I have an element whit this XPath Position: //td[4]/a I try this but does not work: driver.FindElement(By.XPath(".//*[@position='//td[4]/a']")).Click(); Using C# Webdriver and not java, please....

selenium webdriver - xpath locator not working if element's text contains Unicode Characters


selenium,xpath,unicode,selenium-webdriver,webdriver
I'm trying to select an option contained inside a menu. It's not a select menu, but it's styled to appear as such. Anyway, if the text contained inside the menu is in English, I can select it ok. Trouble is, the text I need to select is french so it...

When starting Nightwatch with Grunt, the website server is not started


javascript,node.js,selenium,gruntjs,nightwatch.js
I am using Nightwatch.js to run system tests for a website. I want to automate the tests by running them via grunt. My Gruntfile contains these lines: ... var nightwatch = require('nightwatch'); nightwatch.initGrunt(grunt); ... nightwatch: { options: { standalone: true, test_settings: { "default": { "launch_url": "http://localhost", "selenium_port": 4444, "selenium_host": "localhost",...

Execute javascript within webpage with selenium WebDriver


java,javascript,html,selenium,webdriver
I am trying to execute a javascript method on a webpage with the selenium WebDriver. I am able to execute my own script on the page, but not call the method from the page's HTML. Here is the HTML function Search(){ if(check(document.forms[0],"searchResults")){ var fieldCode = ""; var fieldText = "";...

Junit parameterized testing ,a different thought


java,selenium,junit
Here, I have a custom independent component which accept input as a jar file and identify the junit test classes from it and execute them using the code given below. Result result = JUnitCore.runClasses(cls);//cls is Class<?>instance. Next thing I required is a provision to inject parameters (Assuming that input jar...

Find element by class name


python,parsing,selenium,selenium-webdriver,css-selectors
I'm trying to find one tag using we.find_element_by_css_selector('p.p1.transfer strong.ng-binding').text The problem is that there is sometimes a 'strong' tag before the tag I'm searching for which is very similar but it's class is: class="ng-binding ng-hide" instead of class="ng-binding". But when I try to find it it finds the first tag....

How to get selected option using Selenium WebDriver with Python?


python,selenium,selenium-webdriver,selecteditem,selected
How to get selected option using Selenium WebDriver with Python: Someone have a solution for a getFirstSelectedOption? I'm using this to get the select element: try: FCSelect = driver.find_element_by_id('FCenter') self.TestEventLog = self.TestEventLog + "<br>Verify Form Elements: F Center Select found" except NoSuchElementException: self.TestEventLog = self.TestEventLog + "<br>Error: Select FCenter element...

Return html code of dynamic page using selenium


python,python-2.7,selenium,selenium-webdriver,web-scraping
I'm trying to crawl this website, problem is it's dynamically loaded. Basically I want what I can see from the browser console, not what I see when I right click > show sources. I've tried some selenium examples but I can't get what I need. The code below uses selenium...

Should I use ids to locate elements?


angularjs,selenium,protractor,end-to-end,e2e-testing
Started with Angular and Protractor. It just feels wrong to write some heavy css selectors which will break instant when you change something. Using ID's would make testing way easier. I'm not using any id attribute for styling yet. Are there any drawbacks using ids for testing I haven't considered?...

How do I tell Selenium that an Angular controller has “loaded”


javascript,angularjs,selenium
I've got some UI tests that are attempting to test that a click on an element makes something else appear. There's an existing check for all tests that looks to see if the DOM is Ready, however there's a small amount of time between that even firing and the app.controller()...

Selenium catch popup on close browser


java,selenium,browser
I'm trying to test that when I close my window a popup shows with a warning message. I've tried both driver.close() and driver.quit() after making sure I'm on the proper window but this just terminates the process since my popup doesn't show. I could test it by using the awt...

AndroidDriver constructor rises NullReferenceException


c#,android,selenium-webdriver,webdriver,appium
I use Appium server running on Mac machine and AppiumDriver with c# bindings to execute tests from Windows machine. The issue is that when I create an instance of AndroidDriver its ctor rises a NullReferenceException. When I create an instance of RemoteWebDriver, it works smoothly. This is my code: var...

How to map browser dialog using capybara/selenium


ruby,selenium,capybara
What is the best way to handle browser dialogs (with ok/cancel buttons) using capybara/selenium? The way I found easiest is by running the following: dialog = page.driver.browser.switch_to.alert dialog.accept Any thoughts for a better approach? Whoever downed this post please give a valid reason... it's not helpful to down vote with...

How to write xpath in selenium webdriver for below HTML expressions?


selenium
I wrote xpath for below HTML code i.e. displayed below 1. //a[@text()='Life Insurance'] 2. //span[@text()='Apply now'] But I got element not found exception. If I used Absolute xpath processor then It's working and I wrote own xpath then it thrown exception. Please tell me how to write it. Below are...

selenium exceptions.NoSuchElementException:


python,selenium,webdriver
The html code snippet as: <thead id="addDet:cust:th" class="emp"> <tr id="addDet:cust:ch" class="emp"> <th class="emp" scope="col" id="addDet:cust:ch:j_idt484">S. No.</th> <th class="emp" scope="col" id="addDet:cust:ch:j_idt487">Name <font color="#FA5882">*</font></th> I tried to fill the field as: driver.find_element_by_id("addDet:cust:j_idt487").send_keys("XX") But I am getting the error as: selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element:...

Selenium can't seem to find and click a button on website? - Python


python,selenium,selenium-webdriver,find,element
I am trying to make software that automaticly collects data for me from fiverr.com website. It searches for specific term, and then it should press LOAD MORE button at the end of page, and keep clicking it until it loads all the 'gigs'. Anyway, I have good idea of how...

How to Find class inside in
, using Selenium WebDriver


selenium,webdriver
here is the code: <div class="padding-tlb"> ....Some code.... </div> <article class="non-article-login"> <div class="one-fourth-percent columns-percent">&nbsp;</div> <div class="one-half-percent columns-percent"> <div class="one-fourth-percent columns-percent"> User ID </div> </div> </div> </article> I want to check if exist the class "one-fourth-percent columns-percent". WebElement test = driver.findElement(By.className("one-fourth-percent columns-percent")); But...

Not able to click ExtJS Dropdown button and select list elements - Selenium Webdriver Java


java,selenium,testing,extjs,selenium-webdriver
I am having difficulty in clicking a drop down and selecting option from the list. Below screenshot of the application. Our application uses heavy ExtJS and below is the HTML code for dropdown button and textbox. <div id="combobox-1115-bodyEl" class="x-form-item-body x-form-trigger-wrap-focus" role="presentation" style="width: 325px;"> <div id="ext-gen1273" class="x-hide-display x-form-data-hidden" role="presentation"></div> <input id="ext-gen1272"...

Not able to locate the dropdown value using selenium webdriver


java,selenium,selenium-webdriver
I want to select the value from dropdown. Currently I am able to click on dropdown but not able to select the value from the dropdown. Below are the code which I am using for selecting the value from the dropdown. temp.click(); driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS); Select clickThis = new Select(temp); try{...

Selenium WebDriver: unable to locate element inside iframe using TinyMCE editor


java,selenium,iframe,selenium-webdriver
Maybe my question is similar to this Selenium WebDriver NoSuchElementException: Unable to locate element however I still can't find required element. The element itself looks: body id="tinymce" class="mceContentBody" contenteditable="true" onload="window.parent.tinyMCE.get('compose_295_composeEditor').onLoad.dispatch();" dir="ltr" style="overflow: auto;"> the iframe containing this element is: body id="tinymce" class="mceContentBody" contenteditable="true"...

Python Selenium selecting div class


python,selenium
So I'm writing a script using Selenium but I got stuck at finding a div class. The structure on the website is like this: <div class="field first_name"> <input type="text" placeholder="First Name"></input> </div>` Already tried something like driver.find_element_by_xpath("//field[@first_name]") But it didn't work for some reason, maybe I did it wrong or...

Unable to select text boxes in selenium webdriver through XPath?


selenium,xpath
My HTML <table border="2" style="background:gray"> <tbody> <td class="std"> <input id="ActQ1Revenue" type="text" name="amount" disabled="disabled" maxlength="20" style="background:wheat"> </td> </tr> <tr> <td class="atd"> <input id="ActAprRevenue" type="text" name="amount" maxlength="20"> </td> </tr> <tr> <td class="atd"> <input id="ActMayRevenue" type="text" name="amount" maxlength="20"> </td> </tbody> </table> My XPath...

How to select a text from the autocomplete textbox using selenium


java,selenium,selenium-webdriver,browser-automation
I need to enter some text in a autocomplete textbox. Then I will select a option from that autocomplete option and need to click it. I have tried with the following code: public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub String textToSelect = "headlines today";...

WebDriver Selenium browse file Java


java,eclipse,junit,webdriver
Can't browse file using webdriver. driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS); driver.findElement(By.id("1434461513889_57_7_input.file")).sendKeys("C:\\PDF_V1_COL88810_6L_Frangipani_TL_Fr_P1211089.pdf"); Have this error: NoSuchElementException: Unnable to locate element: {"method":"id","selector":"BatchUploadPlugin_57_fileupload"} HTML code...

Protractor, Done and Expect, why do we need wait?


selenium,selenium-webdriver,jasmine,protractor
I thought Done would make things run synchronously, meaning after I click a link, the click call back would happen after the click, apparently not as this doesn't work. browser.ignoreSynchronization = true; var firstURL = "https://www.google.com/?gws_rd=ssl"; describe("test", function () { browser.get("http://www.google.com"); it("Should be on google url", function () { expect(browser.getCurrentUrl()).toBe(firstURL);...

close and open browser -selenium C# Visual studio


c#,selenium,browser,close
I want to close and then open the browser without close the driver of selenium, using C# I don't want to: driver.Quit(); How Can I close and the open again the browser Chrome?...

Is it possible to save an adobe pdf file using selenium web driver and one click build Jenkins


java,pdf,selenium,jenkins
Here's my dilemma. I'm creating some automation tests using selenium web driver coding in Java. The main output of the software is to load a PDF in adobe acrobat. I'm also using Jenkins which is why my problem has come about as I wont be able to physically see the...

Scrapy not entering parse method


python,selenium,web-scraping,web-crawler,scrapy
I don't understand why this code is not entering the parse method. It is pretty similar to the basic spider examples from the doc: http://doc.scrapy.org/en/latest/topics/spiders.html And I'm pretty sure this worked earlier in the day... Not sure if I modified something or not.. from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.by import...

Value attribute of a text box retains old value even after new value has been keyed in


java,selenium,selenium-webdriver,webdriver
This is the HTML I have for a text box on a form: <input type="text" onblur="javascript:itemLostFocus('18A3461989AC0244E050A20AB17C4671');" onkeydown="javascript:itemChanging('18A3461989AC0244E050A20AB17C4671');" value="972" name="18A3461989AC0244E050A20AB17C4671" maxlength="3" size="3"/> What I do next is update the text box input to 123 from 972. Now if I check the value attribute of the same text box using the getAttribute("value")...

Java Selenium - Can't seem to select an element


java,selenium,xpath,hidden
I'm trying to select an e-mail href to grab the text, but no matter what selections I use to try to select the e-mail, my selection doesn't seem to work and I am curious what other ways might exist to fix the problem. I have used absolute and relative xpath,...