Dropdown CSS Selector in Selenium - java

I have the following page:
http://live.guru99.com/index.php/mobile.html.
I need to click Sort By "name" on the dropdown list in Selenium, trying to do this with this code:
public void f() {
verifyTitle(baseUrl, "Home page");
driver.findElement(By.cssSelector(".level0 ")).click();
verifyTitle(driver.getCurrentUrl(), "Mobile");
Select dd = new Select(driver.findElement(By.cssSelector("select[title=Sort By][css=1]")));
dd.selectByVisibleText("Name");
}
What's wrong with this code? Are quotation marks in right place?

Try to use the following code:
Select dd = new Select(driver.findElement(By.cssSelector("select[title='Sort By']")));
dd.selectByVisibleText("Name");
Hope it helps you!

Related

How to click button and delete input text with Selenium WebDriver

I'm able to navigate this page [here][1] and enter this website [here][2](TOKEN CREATED FOR EACH DEMO FOR THIS LINK)
I'm also able to extract the value from the round count using this xpath here #class,'coefficient'
I can locate the input element on the left hand side but only one text value is deleted. I want to delete all values and enter 50.
It also seems like I can locate the left hand side button because I'm not getting any exceptions or errors but the button is not clickable.
The below two lines:
firstInput.sendKeys(Keys.CONTROL + "a");
firstInput.sendKeys(Keys.DELETE);
is basically to clear the input field, since .clear() is not working as expected in this case, we'd have to do CTRL+a and then delete
A full code will look like this:
driver.manage().window().maximize();
driver.get("https://www.spribe.co/games/aviator");
WebDriverWait wait = new WebDriverWait(driver, 30);
try {
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(),' Got it')]"))).click();
}
catch(Exception e){
e.printStackTrace();
}
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(),'Play Demo ')]"))).click();
String originalWinHandle = driver.getWindowHandle();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(text(),'Yes')]"))).click();
List<String> allHandles = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(allHandles.get(1));
WebElement firstInput = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//label[text()='BET']/ancestor::div[contains(#class,'feature')]/descendant::input")));
firstInput.sendKeys(Keys.CONTROL + "a");
firstInput.sendKeys(Keys.DELETE);
firstInput.sendKeys("20");
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//label[text()='BET']/.."))).click();

Selenium Java code for Listbox selection works on Chrome and IE, but not Firefox

I am working on a public site:
http://preview.harriscountyfws.org/
I am trying to do something simple:
Select an option from a dropdown.
The very same code that works on IE and Chrome, fails on Firefox. No error is generated. It just doesn't pick the right option ("Channel Status") from the Site Type Dropdown.
Any help on this appreciated!
WebElement listbox_element2, we2;
String ariaOwns = "siteType_listbox";
String searchText2 = "Channel Status";
listbox_element2 = driver.findElement(By.cssSelector("span[aria-owns='" + ariaOwns + "']"));
listbox_element2.click();
Sleep(2000);
we2 = driver.findElement(By.xpath("//li[text()='" + searchText2 + "']"));
if (we2 != null) {
we2.click();
}`
You might want to introduce an explicit wait while running test on firefox browser and then print all the drop down options as part of debugging. By making a use of selectByValue(value) method, you can select an item from drop list.
WebElement mySelectElement = driver.findElement(By.id("mySelect"));
Select dropdown= new Select(mySelectElement);
List options = dropdown.getOptions();
for (WebElement option : options) {
System.out.println(option.getText()); //output "option1", "option2", "option3"
}

How to select an item from a dropdown list using Selenium WebDriver with java?

How can I select an item from a drop down list like gender (eg male, female) using Selenium WebDriver with Java?
I have tried this
WebElement select = driver.findElement(By.id("gender"));
List<WebElement> options = select.findElements(By.tagName("Male"));
for (WebElement option : options) {
if("Germany".equals(option.getText()))
option.click();
}
My above code didn't work.
Use -
new Select(driver.findElement(By.id("gender"))).selectByVisibleText("Germany");
Of course, you need to import org.openqa.selenium.support.ui.Select;
Just wrap your WebElement into Select Object as shown below
Select dropdown = new Select(driver.findElement(By.id("identifier")));
Once this is done you can select the required value in 3 ways. Consider an HTML file like this
<html>
<body>
<select id = "designation">
<option value = "MD">MD</option>
<option value = "prog"> Programmer </option>
<option value = "CEO"> CEO </option>
</option>
</select>
<body>
</html>
Now to identify dropdown do
Select dropdown = new Select(driver.findElement(By.id("designation")));
To select its option say 'Programmer' you can do
dropdown.selectByVisibleText("Programmer ");
or
dropdown.selectByIndex(1);
or
dropdown.selectByValue("prog");
Happy Coding :)
Tagname you should mentioned like that "option", if text with space we can use this method it should work.
WebElement select = driver.findElement(By.id("gender"));
List<WebElement> options = select.findElements(By.tagName("option"));
for (WebElement option : options) {
if("Germany".equals(option.getText().trim()))
option.click();
}
You can use 'Select' class of selenium WebDriver as posted by Maitreya. Sorry, but I'm a bit confused about, for selecting gender from drop down why to compare string with "Germany". Here is the code snippet,
Select gender = new Select(driver.findElement(By.id("gender")));
gender.selectByVisibleText("Male/Female");
Import import org.openqa.selenium.support.ui.Select; after adding the above code.
Now gender will be selected which ever you gave ( Male/Female).
Google "select item selenium webdriver" brings up How do I set an option as selected using Selenium WebDriver (selenium 2.0) client in ruby as first result. This is not Java, but you should be able to translate it without too much work. https://sqa.stackexchange.com/questions/1355/what-is-the-correct-way-to-select-an-option-using-seleniums-python-webdriver is in the top 5, again not Java but the API is very similar.
WebElement selectgender = driver.findElement(By.id("gender"));
selectgender.sendKeys("Male");
WebElement select = driver.findElement(By.id("gender"));
List<WebElement> options = select.findElements(By.tagName("option"));
for (WebElement option : options) {
if("Germany".equals(option.getText()))
option.click();
}
To find a particular dropdown box element:
Select gender = new Select(driver.findElement(By.id("gender")));
To get the list of all the elements contained in the dropdown box:
for(int j=1;j<3;j++)
System.out.println(gender.getOptions().get(j).getText());
To select it through visible text displayed when you click on it:
gender.selectByVisibleText("Male");
To select it by index (starting at 0):
gender.selectByIndex(1);
public class checkBoxSel {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
EventFiringWebDriver dr = null ;
dr = new EventFiringWebDriver(driver);
dr.get("http://www.google.co.in/");
dr.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
dr.findElement(By.linkText("Gmail")).click() ;
Select sel = new Select(driver.findElement(By.tagName("select")));
sel.selectByValue("fil");
}
}
I am using GOOGLE LOGIN PAGE to test the seletion option. The above example was to find and select language "Filipino" from the drop down list. I am sure this will solve the problem.

webdriver target="_blank"

Page has image with hyperlink and that hyperlink has target="_blank" and every time i press that image loads new firefox and that hyperlink is redirected to that new firefox web
and i lose all control of that webpage.
Is possilble to remove or change that target="_blank" on hyperlink, bcause i want to load webpage in same webdriver
WebDriver driver = new FirefoxDriver();
driver.get("http://www.page.eu/");
WebElement submit;
submit = driver.findElement(By.xpath("//img[#alt='page']"));
submit.click();
that hyperlink have target="_blank"
i need to change that target somehow by using webdriver + javascript maybe or what?
is it possible?
edited
thanks for suggestions, but still is this problem
i tried to make like Grooveek said but no changes
WebElement labels2 = driver.findElement(By.xpath("//a[#href='http://tahtpage.net']"));
WebElement aa = (WebElement) ((JavascriptExecutor) driver).executeScript("labels2.setAttribute('target','_self')",labels2 );
aa.click();
i have an error
org.openqa.selenium.WebDriverException: null (WARNING: The server did not provide any stacktrace information)
i'm not good at javascrit so i think is problem in that executor
Instead of clicking on the image, you could just directly go to the URL in the link:
WebElement link = (driver.findElement(By.xpath("//img[#alt='page']/parent::*"));
String href = link.getAttribute("href");
driver.get(href);
Try the following:
WebElement labels2 = driver.findElement(By.xpath("//a[#href='http://tahtpage.net']"));
WebElement aa = (WebElement) ((JavascriptExecutor) driver).executeScript("arguments[0].setAttribute('target','_self')",labels2 );
aa.click();
You are getting a null exception because you are using labels2 in your javascript, which doesn't exist in that context. By changing it to arguments[0] Selenium will take the labels2 parameter and reference it in javascript appropriately.
Evaluating javascript in the window will help you to suppress target=blank links
Here's the example from the Webdriver docs
List<WebElement> labels = driver.findElements(By.tagName("label"));
List<WebElement> inputs = (List<WebElement>) ((JavascriptExecutor)driver).executeScript(
"var labels = arguments[0], inputs = []; for (var i=0; i < labels.length; i++){" +
"inputs.push(document.getElementById(labels[i].getAttribute('for'))); } return inputs;", labels);
Adapt it to modify the DOM to throw target="_blank links"
Why don't you wanna use SwitchTo().Window?
I think you should use the SwitchTo().Window as suggested by simeon sinichkin. however, i didn't like his example.Here is simple example.
driver.Navigate().GoToUrl(baseURL);
//Get the Main Window Handle
var baseWindow = driver.CurrentWindowHandle;
// navigate to another window (_blank)
driver.FindElement(By.Id("btn_help")).Click();
Thread.Sleep(2000);
//switch back to Main Window
driver.SwitchTo().Window(baseWindow);
hope that helps
Why don't you use:
target="_self"

How to use HtmlUnit in Java to select an element from a drop down box?

I'm using HtmlUnit in Java to navigate to a web page. From that webpage i need to log in and then go from there. I know how to type in the user name and password but then there is a dropdown box where i need to select one of the options. How do i select an option from a dropdown box in HtmlUnit?
Thanks
You can navigate and manipulate the page <select> elements using HtmlSelect:
WebClient client = ...
Page page = client.getPage(url);
HtmlSelect select = (HtmlSelect) page.getElementById(mySelectId);
HtmlOption option = select.getOptionByValue(desiredOptionValue);
select.setSelectedAttribute(option, true);
The JavaDoc shows that there are a lot of flexible API methods for doing things like this.
Add the follwoing lines:
protected void selectOption(WebElement el, String option)
{
Select select = new Select(el);
select.selectByVisibleText(option);
}
protected WebElement elById(String id)
{
return driver.findElement(By.id(id));
}
// "title" is your drop-down HTML id
public void populateForm(String elValue)
{
selectOption(elById("title"), elValue);
}
Following code:
HtmlSelect select = page.getElementById(mySelectId);
should be:
HtmlSelect select = (HtmlSelect)page.getElementById(mySelectId);

Categories