There is a switch-on/switch-off element on a Web Page. And underneath, here is the source code defined:
<div class = "button">
<label class = "switch">
<input id="sim-switch" class = "hidden" type="checkbox">
<div class = "slider clearfix">
::before
<div class="on-text pull-left">ON</div>
<div class="off-text pull-left">OFF<div>
<div class="inner-slider"></div>
::after
</div>
</label>
</div>
And if was to put this step into selenium automation, I am not sure which part is the "click()" area to make this switch happen. Any ideas?
You can use checkbox for operation, first locate element and use the isChecked() method with if else conditions for operations:
WebElement ele= driver.findElement(By.id("sim-switch"));
if(ele.isSelected()==true)
{
System.out.println("it is clicked");
//append your operations
}
else
{
ele.click();
System.out.println("it is now clicked");
//append your operations
}
Related
Here's my html structure and I am trying to skip a span within a div to get div's text only (which is dynamic) for testing.
<div class="items">
<div class="payment void" id="payment-000000899799">
<div class="payment__details">
<div class="method">CASH <span class="label"><span>Payment Voided</span></span></div>
<div class="date">2/12/2021, 3:02:15 PM</div>
</div>
<div class="payment__details">
<div class="amount">$20.00</div>
<div class="ref">Ref ID: REF-ID-01</div>
</div>
</div>
<div class="payment sale" id="payment-000000899806">
<div class="payment__details">
<div class="method">CASH </div>
<div class="date">2/12/2021, 3:02:21 PM</div>
</div>
<div class="payment__details">
<div class="amount">$100.00</div>
<div class="ref">Ref ID: REF-ID-02</div>
</div>
</div>
</div>
In my step definition I've
List<List<String>> data = capturedData.raw();
WebElement paymentDetails = driver.findElement(By.xpath("(//*[#class='payment__details']/div[#class='method'])[" + data.get(1).get(0) + "]"));
String paymentType = paymentDetails.getText();
System.out.println(paymentType); //This prints CASH Payment Voided
But actually I want only 'CASH' which is a text of div and skip the text 'Payment Voided' of span. And data is coming from a feature file.
How do I get text of div only and skip the text span which is inside the same div?
You cannot skip it directly since it is part of element.
1st Approach
String fulltext = driver.findElement(By.xpath("//*[#class='payment__details']/div[#class='method'][1]")).getText();
String spantext = driver.findElement(By.xpath("//*[#class='payment__details']/div[#class='method'][1]/span")).getText();
//Now replace span text with ""
String output = fulltext.replace(span,"");
2nd Approach
WebElement parent = driver.findElement(By.xpath("//*[#class='payment__details']/div[#class='method'][1]"));
JavascriptExecutor js = (JavascriptExecutor) driver;
String output = (String) js.executeScript("return arguments[0].firstChild.textContent",parent);
I have a dropdown menu with 2 options(option1 and option2).I want to get the NAME of the first option and compare with a string.
I tried something like this but not work for me:
The drop down menu has two items:
-first(default) is "simplex"
-second is "duplex"
The HTML drop down is:
<div class="fieldHelp " id="fieldHelp8352">
<script></script>
<select id="8352" class="lazy-droplist" aria-labelledby="8351" name="pMode:value" style="display: none;">
<option selected value="0">simplex</option>
<option value="1">duplex</option>
</select>
<label id="extendClickArea_8352" style="height:40px; width:100%; position: relative;" class="lazy-droplist">
<span class="ui-selectmenu-button lazy-droplist" tabindex="0" id="8352-button" role="combobox" aria-expanded="false" aria- autocomplete="list" aria-owns="8352-menu" aria-haspopup="true" style="width: 100%;" aria-activedescendant="ui-id-1003" aria- labelledby="ui-id-1003" aria-disabled="false" data-modalfocus="">
<span class="ui-icon ui-icon-triangle-1-s"></span>
<span class="ui-selectmenu-text">simplex</span>
</span>
</label>
<div id="bs-help-modal-sm-8352" style="display: none;" class="bs-help-modal-sm-8352 ui-draggable" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-content"><div class="modal-header ui-draggable-handle">
<button type="button" class="close" aria-label="Close" onclick="closeHelpPopup(event, $('#bs-help-modal-sm-8352'));">
<span aria-hidden="true">×</span></button>
.....
.....
</div>
<script>
$('#bs-help-modal-sm-8352').draggable({ handle: '.modal-header' });
</script>
</div>
Noticed that the code is somehow grayout,inactive but when I tried to extract test "simplex" ,not said that the menu is hidden or something...
Java code is:
Select select = new Select(driver.findElement(By.name("simplex")));
WebElement option = select.getFirstSelectedOption();
String defaultItem = option.getText();
System.out.println(defaultItem);->this variable is empty :(
if (defaultItem == "simplex") {
System.out.println("Is Simplex");
} else {
System.out.println("Is Duplex");
Where I do something wrong because defaultItem is empty...
Thks
In your case, I cant see name attribute with "simplex" anywhere in the code provided by you. Also, a problem I can see in HTML code is it does not have any value for a selected attribute that's why you getting the empty value:
<option selected="" value="0">simplex</option>
Try below method:
Select select = new Select(driver.findElement(By.id("8352")));
List<WebElement> options = select.getOptions();
int optionssize= options.size();
for(int i=0;i<optionssize;i++)
{
if(options.get(i).getText().equals("Simplex"))
{
System.out.println("Is Simplex available at"+i);
break;
}
}
Solved.
The solution was:
String Text = driver.findElement(By.id("the_direct_path_to_this_span_<span class="ui-selectmenu-text">simplex</span>")).getText();
if(text.equals("Simplex"))
{
System.out.println("Is Simplex");
} else {
System.out.println("Is NOT Simplex");
}
I am using the code below
WebElement inputele = driver.findElement(By.className("class_name"));
String inputeleval = inputele.getAttribute("value");
System.out.println(inputeleval);
but the value is empty. The HTML is below.
<div id="main">
<div id="hiddenresult">
<div class="tech-blog-list">
<label for="Question">1st Question</label>
<input id="txt60" class="form-control" type="text" value="sddf sd sdfsdf sdf sdfsdf sdfsdfsd fsd" />
</div>
</div>
<div class="pagination_main pull-left">
<div id="Pagination">
<div class="pagination">
<a class="previous" onclick="PreviousBtnClickEvent();" href="javascript:void(0)">Previous</a>
<a id="pg59" class="ep" onclick="PaginationBtnClickEvent(this);" href="javascript:void(0)" name="Textbox">1</a>
<a id="pg41" class="ep" onclick="PaginationBtnClickEvent(this);" href="javascript:void(0)" name="Textbox">2</a>
<a id="pg40" class="ep" onclick="PaginationBtnClickEvent(this);" href="javascript:void(0)" name="Textarea">3</a>
<a id="pg60" class="ep current" onclick="PaginationBtnClickEvent(this);" href="javascript:void(0)" name="Textbox">4</a>
</div>
</div>
</div>
</div>
Try using WebDriverWait to wait until element fully loaded on page and visible as below :-
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement inputele= wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("class_name")));
String inputeleval = inputele.getAttribute("value");
System.out.println(inputeleval);
Note :-By.className("class_name") will give that element which class attribute equal to class_name. Make sure which element you want to locate is unique element with class attribute equal to class_name otherwise wise it will give first element with condition true.
Hope it will work..:)
Looks like your code is pretty close but you have the wrong class name? In your code above, you had "class_name" instead of "form-control". I'm assuming that was some sample code and not the actual code you are using? There is only one INPUT in the HTML and the code below should work. It also has an ID so that should be more specific in case there are more than one INPUTs on the page.
WebElement inputele= driver.findElement(By.className("form-control"));
String inputeleval = inputele.getAttribute("value");
System.out.println(inputeleval);
I am automating extracting product variations on Amazon and I have the following HTML markup:
<ul
class="a-nostyle a-button-list a-horizontal a-spacing-top-micro swatches swatchesSquare imageSwatches">
<!-- Please note that in className never append a class with prefix as 'swatch'. It would break something in the twister JS -->
<li id="color_name_0" class="swatchSelect" data-dp-url="" title="Click to select White">
<span class="a-list-item">
<div class="tooltip">
<span class="a-declarative" data-swatchthumb-action="{"dimIndex":1,"dimValueIndex":0}" data-action="swatchthumb-action">
<span id="a-autoid-11" class="a-button a-button-thumbnail a-button-toggle">
<span class="a-button-inner">
<button id="a-autoid-11-announce" class="a-button-text" type="button">
<span class="xoverlay" />
<div class="">
<div class="">
<img style="height:36px; width:36px" alt="White"
src="http://ecx.images-amazon.com/images/I/41IrdkWxWOL._SS36_.jpg"/>
</div>
<div class="" style=" " />
</div>
</button>
</span>
</span>
</span>
</div>
</span>
</li>
</ul>
I'm using the following XPath to extract the XPath of all colors.
.//*[#id='variation_color_name']/ul/li/span/div/span/span/span/button
Now I want to extract the alt attribute of each item but when I try using getAttribute("alt") it does not return anything. In this case the alt text would be "White". The product I am viewing is: http://www.amazon.com/dp/B00J46VVKE . I'm using Java.
When you have an id attribute there is no need to go to xpath's i believe, unless you have many button's with same id. However here's how you can get the attribute of the img element -
WebElement btn = driver.findElement(By.id("a-autoid-11-announce"));
String imgColor = btn.findElement(By.tagName("img")).getAttribute("alt");
Hope this helps.
You can use this code:
public class Stackoverflow extends Init {
#Test
public void testToGetAltAttribute() throws InterruptedException {
System.out.println("Get Attribute....");
// this element has alt attribute hence that will be displayed.
assertAndVerifyElement(By.cssSelector("#landingImage"));
System.out.println("\n#landingImage\n=====================");
System.out.println(getAttributeOfGivenElement(By.cssSelector("#landingImage"), "alt"));
// this element do not has alt attribute hence that will not be
// displayed.
// it will display msg "element do not have altattribute"
assertAndVerifyElement(By.id("productTitle"));
System.out.println("\n#productTitle\n=====================");
System.out.println(getAttributeOfGivenElement(By.id("productTitle"), "alt"));
}
public String getAttributeOfGivenElement(By element, String attributeName) {
WebElement webElement = getWebDriver().findElement(element);
if (webElement.getAttribute(attributeName) != null) {
return webElement.getAttribute("alt");
} else {
return "element do not have " + attributeName + "attribute";
}
}
public void assertAndVerifyElement(By element) throws InterruptedException {
boolean isPresent = false;
for (int i = 0; i < 5; i++) {
try {
if (getWebDriver().findElement(element) != null) {
isPresent = true;
break;
}
} catch (Exception e) {
// System.out.println(e.getLocalizedMessage());
Thread.sleep(1000);
}
}
Assert.assertTrue(isPresent, "\"" + element + "\" is not present.");
}
}
If you want all the colors, you will want to grab the IMG elements that contain the ALT attribute. Your XPath ends at a BUTTON. Try the code below.
List<WebElement> colors = driver.findElements(By.cssSelector("ul.imageSwatches img"));
for (WebElement color : colors)
{
System.out.println(color.getAttribute("alt"));
}
The CSS selector is read find a UL tag that has the class imageSwatches then find all descendant IMG tags. You loop through that collection of IMG tags and output the ALT text.
I am trying to find button add to cart is present or not using loop from all item box from following code
<div class="page-body">
<div class="product-selectors">
<div class="product-filters-wrapper">
<div class="product-grid">
<div class="item-box">
<div class="item-box">
<div class="item-box">
<div class="item-box">
</div>
in each item box folowing code
<div class="item-box">
<div class="product-item" data-productid="20">
<div class="picture">
<div class="details">
<h2 class="product-title">
<div class="product-rating-box" title="1 review(s)">
<div class="description"> 12x optical zoom; SuperRange Optical Image Stabilizer </div>
<div class="add-info">
<div class="prices">
<div class="buttons">
<input class="button-2 product-box-add-to-cart-button" type="button" onclick="AjaxCart.addproducttocart_catalog('/addproducttocart/catalog/20/1/1 ');return false;" value="Add to cart">
</div>
</div>
</div>
</div>
</div>
I need to find that all itembox have add to cart button present or not using loop. if anyone can help please
I suggest to avoid looping if not necessary. You do not need to do the loop to find out unless there is an explicit need of doing so. You can find the count of Add to cart button and compare with a known value
By byCss = By.cssSelector(".item-box>div input[value='Add to cart']");
int cartCount = driver.findElements(byCss).size();
if (cartCount != 4){
//fail the test
}
If you exactly one to looping and check if the input button exist or not.
By itemBoxes = By.className("item-box");
By button = By.cssSelector("[type='button'][value='Add to cart']");
List<WebElement> webElementList = driver.findElements(itemBoxes);
for (WebElement element: webElementList){
//simply taking size if exist it will return 1
if (element.findElements(button).size() != 1){
//fail
}
}
you can use searching by xpath inside of the loop.
Something like
".//input[#value='Add to cart'][1]"
".//input[#value='Add to cart'][2]"
".//input[#value='Add to cart'][3]"
etc
not sure that this xpath is correct, but generally it will work for you, bro.
Or something like this:
string xpath=".//input[#value='Add to cart']";
var AddToCartBtnsList = driver.findElements(By.Xpath(xpath));
foreach(IWebElement button in AddToCartBtnsList )
{
button.click();
}