Selenium-WebElement - Notes By ShariqSP
WebElement Methods
Explore web elements and behaviorsAll Superinterfaces:
SearchContext, TakesScreenshot
All Known Implementing Classes:
RemoteWebElement
WebElement Interface
Represents an HTML element. Generally, all interesting operations to do with interacting with a page will be performed through this interface.
Methods:
- void click()
- void sendKeys(CharSequence...ch)
- void submit()
- void clear()
- String getText()
- String getAttribute()
- String getTagName()
- String getCssValue()
- Dimension getSize()
- Point getLocation()
- Rectangle getRect()
- boolean isDisplayed()
- boolean isSelected()
- boolean isEnabled()
Method Explanations:
void click()
Click this element. If this causes a new page to load, you should discard all references to this element and any further operations performed on this element will throw a StaleElementReferenceException.Note
that if click() is done by sending a native event (which is the default on most browsers/platforms) then the method will _not_ wait for the next page to load and the caller should verify that themselves. There are some preconditions for an element to be clicked. The element must be visible, and it must have a height and width greater than 0.Example : driver.findElement(By.xpath("//strong[text()='Featured products']/../..//a[text()='$25 Virtual Gift Card']")).click();
void sendKeys(CharSequence... keysToSend)
Use this method to simulate typing into an element, which may set its value.driver.findElement(By.xpath("//input[contains(@id,'FirstName')]")).sendKeys("shariq");
void submit()
If this current element is a form, or an element within a form, then this will be submitted to the remote server. If this causes the current page to change, then this method will block until the new page is loaded.driver.findElement(By.xpath("//input[contains(@id,'register-button')]")).submit();
void clear()
If this element is a form entry element, this will reset its value.driver.findElement(By.xpath("//input[contains(@id,'FirstName')]")).clear();
String getText()
Get the visible (i.e. not hidden by CSS) text of this element, including sub-elements.String s = driver.findElement(By.xpath("//h1[text()='Register']")).getText();
String getAttribute(String name)
Get the value of the given attribute of the element. Will return the current value, even if this has been modified after the page has been loaded. More exactly, this method will return the value of the property with the given name, if it exists. If it does not, then the value of the attribute with the given name is returned. If neither exists, null is returned. The "style" attribute is converted as best can be to a text representation with a trailing semicolon. The following are deemed to be "boolean" attributes, and will return either "true" or null: Finally, the following commonly mis-capitalized attribute/property names are evaluated as expected: If the given name is "class", the "className" property is returned. If the given name is "readonly", the "readOnly" property is returned. Note: The reason for this behavior is that users frequently confuse attributes and properties. If you need to do something more precise, use getDomAttribute(String) or getDomProperty(String) to obtain the result you desire.String type =driver.findElement(By.xpath("//input[contains(@id,'ConfirmPassword')]")).getAttribute("type"); System.out.println(type); String style=driver.findElement(By.xpath("//span[text()='Wait...']")).getAttribute("style"); System.out.println(style); OUTPUT : display: none;
String getTagName()
Get the tag name of this element. Not the value of the name attribute: will return "input" for the element <input name="foo" />.String tag=driver.findElement(By.xpath("//span[text()='Wait...']")).getTagName(); System.out.println(tag);
String getCssValue(String propertyName)
Get the value of a given CSS property. Color values could be returned as rgba or rgb strings. This depends on whether the browser omits the implicit opacity value or not. For example if the "background-color" property is set as "green" in the HTML source, the returned value could be "rgba(0, 255, 0, 1)" if implicit opacity value is preserved or "rgb(0, 255, 0)" if it is omitted.Note
that shorthand CSS properties (e.g. background, font, border, border-top, margin, margin-top, padding, padding-top, list-style, outline, pause, cue) are not returned, in accordance with the DOM CSS2 specification - you should directly access the longhand properties (e.g. background-color) to access the desired values.String cssproperty = driver.findElement(By.xpath("//span[text()='Wait...']")).getCssValue("display"); System.out.println(cssproperty);
Dimension getSize()
Get the width and height of the rendered element.System.out.println(driver.manage().window().getSize()); Output : (1051, 798)
Point getLocation()
Get the location of the top-left corner of the rendered element.System.out.println(driver.manage().window().getPosition());
Rectangle getRect()
Get the location and size of the rendered element.System.out.println(driver.manage().window().getRect()); Rectangle rect = driver.findElement(By.xpath("//h1[text()='Register']")).getRect(); System.out.println(rect.height); System.out.println(rect.width); System.out.println(rect.getWidth()); System.out.println(rect.getHeight()); System.out.println(rect.x); System.out.println(rect.y); System.out.println(rect.getX()); System.out.println(rect.getY());
boolean isDisplayed()
Check if this element is displayed or not.boolean b = driver.findElement(By.xpath("//span[text()='Wait...']")).isDisplayed(); System.out.println(b); Output : false boolean b = driver.findElement(By.xpath("//h1[text()='Register']")).isDisplayed();
boolean isSelected()
Check if this element is selected. This operation only applies to input elements such as checkboxes, options in a select and radio buttons.boolean selected = driver.findElement(By.xpath("//input[contains(@id,'gender-male')]")).isSelected(); System.out.println(selected);
boolean isEnabled()
Check if this element is enabled.This will generally return true for everything but disabled input elements.boolean enabled = driver.findElement(By.xpath("//input[contains(@id,'gender-male')]")).isEnabled(); System.out.println(enabled);
findElements()
Find all elements within the current context using the given mechanism.
When using XPath, be aware that WebDriver follows standard conventions: a search prefixed with "//" will search the entire document, not just the children of this current node. Use ".//" to limit your search to the children of this WebElement.
This method is affected by the 'implicit wait' times in force at the time of execution. When implicitly waiting, this method will return as soon as there are more than 0 items in the found collection, or will return an empty list if the timeout is reached.
Assignments
Fetch item name and discount and display.
Use the below url : https://demoapps.qspiders.com/ui/table?scenario=1
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
ChromeDriver driver = new ChromeDriver();
driver.get("https://demoapps.qspiders.com/ui/table");
driver.manage().window().maximize();
Thread.sleep(2000);
List itemName = driver.findElements(By.xpath("//td[@class='px-6 py-4'][3] | //th[@scope='row']"));
int a=0;
for(WebElement i : itemName)
{
if(a%2!=0)
System.out.println();
System.out.print(". "+i.getText()+" ");
}
Thread.sleep(5000);
driver.close();
}
Take a screenshot for the right arrow button on the demo webpage.
public static void main(String[] args) throws IOException, InterruptedException {
System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
ChromeDriver driver = new ChromeDriver();
driver.get("https://demowebshop.tricentis.com/");
driver.manage().window().maximize();
WebElement we = driver.findElement(By.xpath("//*[@id=\"nivo-slider\"]/div[2]/a[2]"));
Actions act = new Actions(driver);
act.moveToElement(we).perform();
File src = we.getScreenshotAs(OutputType.FILE);
File trg = new File("./snapshots/navBar.png");
FileHandler.copy(src, trg);
Thread.sleep(5000);
driver.close();
}
Login first, then add an item to the cart and take a screenshot of the shopping cart link once the product has been added to the shopping cart.
do it your
Try to click on Shopperstack login button using script
After executing the script, the login button will not be clicked due to the time taken to load the graphics. To handle this, you can use Thread.sleep, but it may not be efficient. Instead, use implicit or explicit waits to wait for the element to be clickable.
WebElement Interview Questions
- What is a WebElement in Selenium WebDriver?
- How do you find a WebElement on a web page?
- What are the different methods available in WebElement interface?
- Explain getText() method in WebElement.
- How do you simulate a click action on a WebElement?
- Explain sendKeys() method in WebElement.
- What is the purpose of clear() method in WebElement?
- How do you retrieve attributes of a WebElement?
- Explain isSelected() method in WebElement.
- What is submit() method in WebElement?
- How do you perform drag and drop action using WebElement?
- Explain getAttribute() method in WebElement.
- What is isEnabled() method in WebElement?
- How do you retrieve CSS property values of a WebElement?
- What is getLocation() method in WebElement?
- Explain getSize() method in WebElement.
- How do you use findElement() method within another WebElement?
- Explain getTagName() method in WebElement.
- What is getRect() method in WebElement?
- How do you perform right-click action on a WebElement?
Multiple Choice Questions (MCQs)
- Which method is used to retrieve the text from a WebElement?
- getText()
- retrieveText()
- readText()
- getTextValue()
- What method is used to check if a WebElement is displayed on the web page?
- isDisplayed()
- isVisible()
- displayStatus()
- isPresent()
- Which method is used to clear the text from an input field?
- clearText()
- deleteText()
- clear()
- removeText()
- How do you retrieve the value of an attribute of a WebElement?
- getAttribute()
- retrieveAttribute()
- getAttrValue()
- readAttribute()
- Which method is used to check if a checkbox or radio button is selected?
- isSelected()
- isChecked()
- isClicked()
- isToggled()
- What is the purpose of the submit() method in WebElement?
- To submit a form.
- To click a button.
- To clear input fields.
- To retrieve text.
- Which method is used to retrieve the size of a WebElement?
- getSize()
- getDimension()
- getSizeOf()
- getBounds()
- What does isEnabled() method in WebElement determine?
- Whether the element is clickable.
- Whether the element is visible.
- Whether the element is enabled.
- Whether the element is selected.
- Which method is used to retrieve the tag name of a WebElement?
- getTag()
- getTagName()
- tagName()
- retrieveTagName()
- What method is used to perform right-click action on a WebElement?
- rightClick()
- contextClick()
- performRightClick()
- clickRight()