how to select a value from dynamic searchbox in selenium webdriver java? - selenium

enter image description here
I have to select a name from this searchbox based on my input value. How I can achieve this.

#send something to the input
input=driver.find_element_by_xpath("//input[#role='combobox']") #xpath to input box
input.send_keys("something")
#find the drop down element and scroll to that element
options = driver.find_element_by_xpath("xpathtotheoptiondropdown")
driver.execute_script("arguments[0].scrollIntoView();", option)
#click that element
option.click()

Option 1:
If html tag for Account name is <select>...</select>, you can use org.openqa.selenium.support.ui.Select
See https://www.guru99.com/select-option-dropdown-selenium-webdriver.html
Option 2:
Use relationship parent-child of elements.
See Selenium Java : Dropdown items are updated dynamically
and https://www.tutorialspoint.com/locating-child-nodes-of-webelements-in-selenium

Related

Unable to recognize Element with relative xpath or other locator

I am facing an issue where I am unable to locate Element on webpage with any type of locator expect Absolute xpath. Here are details:
URL : https://semantic-ui.com/modules/dropdown.html#selection
Required Element Screen shot:
Manually created Xpath Screen shot( Please note that I am able to recognize Element in web application with manually created xpath but Same xpath is not working in selenium code)
But Same xpath is not working in selenium script.
PLEASE NOTE THAT I AM ABLE TO IDENTIFY SAME OBJECT WITH Absolute xpath
Please help to me to understand reason for this.
Here is code:
public static WebDriver driver;
public static void main(String[] args) {
driver= new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://semantic-ui.com/modules/dropdown.html");
//Selection
driver.findElement(By.xpath("//div[#class='ui selection dropdown upward']")).click();
driver.findElement(By.xpath("//div[#class='menu transition visible']/div[text()='Female']")).click();
System.out.println("Done");
This may be issue with your first x-path. You may try the following code. It may work.
driver.findElement(By.xpath("//div[#class='ui selection dropdown']").click();
driver.findElement(By.xpath("//div[#class='menu transition visible']/div[text()='Male']").click();
You are missing a preceding wildcard in you driver.FindElement XPath.
Instead of driver.findElement(By.xpath("//div..."));, do driver.findElement(By.xpath("//*div..."));.
Currently, what your code is doing is telling the XPath locator to find a first level div (not easily possible, as the first item is almost always the document body), but the wildcard of "*" tells it that it can look for the div at any level.
As an aside, please edit your answer up top with actual code instead of pictures so others with the same problem can find their solution easier.
Longshot:
You are using Chrome to look at the source, but Selenium is using Firefox.
There is a chance that the source is rendered differently between the two browsers. Specifically, your xpath is relying on an exact match of class. I do know that FireFox is notorious for modifying source output.
I haven't done any testing but I would not be surprised if the class is in a different order and it's failing on an exact match.
There are two solutions if that is the case:
Don't do a single exact match (xpath = "") but instead do a mix of contains joined with && (contains ui && contains selection && dropdown)
Don't rely on the output from the console tab. Instead "View Page Source" and view what is actually being sent instead of what is being interpreted by the browser
Find the dropdown container element firstly, then use it to find self descendant, like option etc.
driver.get("https://semantic-ui.com/modules/dropdown.html");
// find dropdown container element
WebElement dropdownWrapper = driver.findElement(
By.xpath("//div[#class='html']/div[input[#name='gender']]"));
// expand drop down options by click on the container element
dropdownWrapper.click();
// or click the down arrow
dropdownWrapper.findElement(By.css('i')).click();
// select option
dropdownWrapper.findElement(By.xpath(".//div[text()='Female']")).click();
To locate the element with text as Gender and select the option Female you can use the following Locator Strategy :
Code Block :
System.setProperty("webdriver.chrome.driver", "C:\\path\\to\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://semantic-ui.com/modules/dropdown.html#selection");
driver.findElement(By.xpath("//div[#class='another dropdown example']//div[#class='ui dropdown selection']")).click();
driver.findElement(By.xpath("//div[#class='another dropdown example']//div[#class='ui dropdown selection active visible']//div[#class='menu transition visible']//div[#class='item' and contains(.,'Female')]")).click();
System.out.println("Gender Female selected.");
Console Output :
Gender Female selected.
This might be helpful to clearify how selectors are working in general:
.(dot): Dot at starting represents the current node. It tells us that the processing will start from the current node.
. .(double dot): It will select parent of current node. For example, //table/. . will return div element because div is the parent of table element.
‘*’: is used to select all the element nodes descending from the current node. For example:
/table/*: It will select all child elements of a table element.
//*: It will select all elements in the document.
//*[#id = ‘username’]: It will select any element in document which has an attribute named “id” with the specified value “username”.
#: It represents an attribute which selects id, name, className, etc. For example:
#id: It will select all elements that are defined with the id attribute in the document. No matter where it is defined in the document.
//img/#alt: It will select all the img elements that are defined with the #alt attribute.
//td[#*]: It will select all td elements with any attribute.
Here is a link to the article:
https://www.scientecheasy.com/2020/07/selenium-xpath-example.html/

How to click an element with reference to another web element in Selenium WebDriver(Java)?

There are many span tags as mentioned in the image below and each has its own a-tag with unique id as "chooseitem". I need to choose particular a tag using names in the span tags.
Need to click the a-tag button using the text Mayo Chicken from the above HTML snippet in the image.
I have tried the below Selenium script
WebElement select = driver.findElement(By.xpath("//*[contains(text(),'Mayo Chicken (Single)')]"));
WebElement add = select.findElement(By.id("chooseitem"));
It doesn't work for me.
driver.findElement(By.id("chooseitem"));
The above code chooses the first item in the page by default as its id is also 'chooseitem', but need to define what to be chosen.
Can anybody help me out?
We need to get the common parent(ancestor) element of the chicked and the clickable 'a' tag, then we can navigate to the tag 'a'. Below xpath should ideally work.
"//span[contains(text(),'Mayo chicken')]/ancestor::div[4]//a"
Note: Here i have used div[4] because fourth parent is the common ancestor for 'Mayo chicken' and tag 'a'.
For more details about different xpath axis refer this->https://www.w3schools.com/xml/xpath_axes.asp
Hope this helps you. thanks.
You can do that by using the xpath position, press F12 for developer tools click on "Select element button", click the element that interests you on the page, as in your picture you will see one or more lines highlighted, right click the line -> Copy -> Copy xpath. You will have something like the line below:
//*[#id="comment-76500216"]/td[2]/div/span[1]
The xpath position will be:
//td[2]/div/span[1]
You can use that when you have multiple elements that share the name or id or so on.
And you will have:
WebElement select = driver.findElement(By.xpath("//td[2]/div/span[1]"));
PS: I used google chrome

Why my Selenium web driver is not clicking on Element identified by id?

My Selenium web driver is not clicking on this tree node. I don't know exactly what we say it tree node or something else so this is image and I highlighted the element.
This right arrow part on which I want to click
And this is my code:
//wait.until(ExpectedConditions.elementToBeClickable(By.id("iconDiv")));
WebElement taskdropElementid = driver.findElement(By.id("iconDiv"));
System.out.println(taskdropElementid.getAttribute("class"));
if(taskdropElementid.getAttribute("class").equals("RightArrow"))
taskdropElementid.click();
Printing statement is giving me output dropdown. I think it should give RightArrow and when I am uncommenting wait part then it is continuously wait for the element to be clickable.
What am I doing wrong?
Printing statement is giving me output dropdown
That means there are multiple elements with the same id iconDiv and unfortunately you're locating other element instead which has class name dropdown.
If you want to locate element with class name RightArrow, You should try using By.cssSelector() to locate it uniquely as below :-
WebElement taskdropElementid = driver.findElement(By.cssSelector("div#iconDiv.RightArrow"));
taskdropElementid.click();

When and how can I locate an element by tag name using Selenium WebDriver? Please explain with an example

I have used most of the element locators while testing with Selenium, but very low frequently used the 'TagName' locator. Please give an example.
Now supposing, a software web element does not have any ID or Class Name, then how can we locate that element in Selenium WebDriver? The answer is there are many alternatives of the Selenium WebDriver element locators and one of them is locating an element by tag name.
Locating an element by tag name is not too much popular because in most of cases, we will have other alternatives of element locators. But yes, if there is not any alternative then you can use the element's DOM tag name to locate that element in webdriver.
Here you can select the tagname as a locator like:
// Locating the element by tagName and store its text in variable 'dropdown'.
String dropdown = driver.findElement(By.tagName("select")).getText();
Thanks to the deprecation of By.tagName you should use By.css for Shah's answer...
String dropdown = driver.findElement(By.css("select")).getText();
We use the actual name of the tag like <a> for anchor and <table> for table and input for <input>. This helps to get all the elements with a given tag name.
Example: to select the first element of a given input
var dialog = driver.FindElement(By.ClassName("ladialog"));
var save = dialog.FindElements(By.TagName("input"))[0];
save.Click();
Also importantly, the tagName locating strategy can be used to get or fetch all the links on a webpage and print them to console. Try this:
// Get all links in a webpage
List<WebElement> allLinks = driver.findElements(By.tagName("a"));
System.out.println("Links count is: " + allLinks.size());
for(WebElement link : allLinks)
System.out.println(link.getText());

how to select the check box using selenium?

How to select the checkbox which has a dynamically changing ID and XPath?
Multiple ways:
You should look at a pattern like id or name somoething like
CT_CHKBox_157, CT_CHK_158 etc.. For example, to click the first
Checkbox having a pattern of Ids
You can use a dynamic xpath like driver.findelement(By.xpath(//input[starts-with(#id,'CT_CHK'][1]).click()
Identify the Unique Element which are close ancestors to the
Checkbox in question and reach out to it through xpath or css path
relatively or through indexing from within.
Hope that clarifies.
Have you tried XPath by position? Ultimately the check boxes are like buttons or link that can be clicked so driver.findElement(By.xpath("//xpath by position")).click();
Alternativey you might want to use JavaScript:
((JavascriptExecutor) driver).executeScript("return document.getElementsByName('ChkboxValue')[0].checked;");
Hope this helps.
Selenium uses what is called locators to find and match the elements.There are 8 locators strategies included in Selenium:
Identifier
Id
Name
Link
DOM
XPath
CSS
UI-element
you can try using any other Locator in the list.