I have been trying to automate a search using Selenium. I simply want to search terms (say Pink Floyd) but the file type should be pdf. Here is what I have done so far:
//Query term
WebElement element = driver.findElement(By.name("as_q"));
String finalQuery = "pink floyd";
element.sendKeys(finalQuery);
//File type selection
WebElement elem = driver.findElement(By.id("as_filetype_button"));
elem.sendKeys("Adobe Acrobat pdf (.pdf)");
driver.findElement(By.xpath("/html/body/div[1]/div[4]/form/div[5]/div[9]/div[2]/input[#type='submit']")).click();
This puts the term in the appropriate place and the drop down for file types are expanded but pdf option is not selected. Any help?
I am using Selenium 2.53.0.
EDIT
The following code segment perfectly worked as per the accepted answer for this question. However, all on a sudden the code segment is not working. I am a bit surprised to find this out. Previously, I was able to select PDF automatically with the following code segment but now, nothing gets selected.
WebElement element = driver.findElement(By.name("as_q"));
String finalQuery = "pink floyd";
element.sendKeys(finalQuery);
driver.findElement(By.id("as_filetype_button")).click();
driver.findElement(By.xpath("//li[#class=class-name][#value='pdf']")).click();
This is how i do it, find the li that matches the class='goog-menuitem' and value='pdf', i inspected the element. You can go directly with value='pdf' but just to make sure we are looking at the file type dropdown we added the class.
driver.findElement(By.id("as_filetype_button")).click();
driver.findElement(By.xpath("//li[#class='goog-menuitem'][#value='pdf']")).click();
You can still declare it with WebElement, i just prefer it shorthand. Hope this helps.
Related
I am using Selenium WebDriver to automate something. It requires filling a form that involves selecting a value from a select2 dropdown. This is the code snippet that I am using-
final By SELECT_DIV = By.id("s2");
click(SELECT_DIV);
final By INPUT = By.cssSelector(".select2-drop-active .select2-input");
waitForVisibilityOfElement(INPUT);
enterCharSequence(INPUT, "someData");
waitForJSandJQueryToLoad(30);//30 seconds
final By LIST_ITEM = By.cssSelector(".select2-drop-active ul.select2-results li.select2-result-selectable");
click(LIST_ITEM);
FYI, there are no unique ids assigned to some of these elements and hence I used css selectors for locating them.
This code works but it sometimes throws a StaleElementReferenceException. This is the error:
org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Selenium version : 2.53
So, I want to know if there is any way I could avoid this. I read a few posts about it but they were not of much help.
Let me know if you need more information. Any help would be appreciated.
'StaleElementReferenceException' means that the element has changed. It is in another div, another span or the its properties changed. Selenium may found it but it changed the very second you tried to click on it.
You need to search for the same element again and wait for it to be clickAble or visible. For example:
WebDriverWait wait = new WebDriverWait(driver, 20);
WebElement button =
wait.until(ExpectedConditions.
elementToBeClickable(By.id("btnLogin")));
I'm designing tests in Selenium WebDriver Framwework and I would like to insert text into fields in login box.
Here is a website www.fitandjump-widzew.pl
After click on "Zaloguj" button in top right corner, Login box appears.
I would like to insert text into E-mail inputfield.
Here is my code:
WebElement emailInput = driver.findElement(By.xpath("//[#id=\"inputFields\"]"));
emailInput.click();
emailInput.sendKeys("grzegorzrudniak#gmail.com");
After execution I get this error:
org.openqa.selenium.ElementNotVisibleException: element not visible
Can anyone help me to insert text into this field?
Please take a look at second input in this box, it's called "Hasło".
Xpath of this two fields is the same.
Additional question is how to insert text into "Hasło" inputfield as well?
Just make sure the locator you are using identifies single element [Unique]. Use single quotes in xpath and use correct xpath, you haven't used any html tag after // I've used * which means it is valid for all HTML tags.
WebElement emailInput = driver.findElement(By.xpath("//*[#id='inputFields']"));
//emailInput.click(); // no need to click on the element, you can directly type.
emailInput.sendKeys("grzegorzrudniak#gmail.com");
I am using selenium-RC for my automation with java (Eclipse Kepler) . I am facing some issues with a selection of a option in a drop down list which is not in select tag it is in span.
I want to test a page where their is a drop-down list for selection of city name. the drop-down appears only when I give some value e.g for "Bangalore" I have to type "ban" so the drop-down appears and then I select the city Bangalore either with "mouse click" or either with "down-arrow and enter key" but when I run my selenium rc script it fails after typing "ban" the drop-down doesn't appears. i tried using both xpath and id in select command,click command. I am stuck over here please please someone help me to solve this issue.I think it is dynamic and based on JavaScript functions.One more ..The next two drop down are depended on the first drop-down(i.e the second and third drop-down are hidden and first drop-down is shown by_default.)
I am sending the link of page where i am trying to test script: https://pizzaonline.dominos.co.in
I tried using following commands:-
1:
w.click("//*[#id='homedeliveryform']/div[1]/span/a/span[1]");
w.click("//*[#id='ui-active-menuitem']");
2:
w.type("//*[#id='homedeliveryform']/div[1]/span/input","ban");
w.click("//*[#id='ui-active-menuitem']");
3:
w.select(" id=combobox", "value=BANGALORE");
4:
w.type(" id=combobox", "value=BANGALORE");
I've had a similar problem. This is how I solved it:
Find the arrow button in the combobox and click it, the dropdown list will appear.
The dropdown list doesn't really have anything to do with the combobox, it is a separate list wich is just displayed in a correct position so that it looks like it belongs to the combobox. The dropdown list is actually an <ul>-element, which doesn't seem to be very easily found. Anyway there are many <li>-elements with <a>-elements in them, and those hold the texts.
As i can see you are trying to select a webelement(Bangalore) from a dropdown which is not visible till the time you click on it. Here are the ways by which you are able to select a hidden web element.
1st way: it is not the problem to click any element using the same js. As you know how to get any option the last actions remaning is to perform a click. This should work for you:
WebElement hiddenWebElement =driver.findElement(By(..selector of the element....));
((JavascriptExecutor)driver).executeScript("arguments[0].click()",hiddenWebElement);
2nd way:
String cssSelector= ...//i gave them in your previous question
JavascriptExecutor js = (JavascriptExecutor) driver;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("var x = $(\'"+cssSelector+"\');");
stringBuilder.append("x.click();");
js.executeScript(stringBuilder.toString());
3rd way: using actions builder, advanced user actions API. You can read about it here And code will be smth like that:
WebElement mnuElement;
WebElement submnuElement;
mnEle = driver.findElement(By.Id("mnEle")).click();
sbEle = driver.findElement(By.Id("sbEle")).click();
Actions builder = new Actions(driver);
// Move cursor to the Main Menu Element
builder.moveToElement(mnEle).Perform();
// Giving 5 Secs for submenu to be displayed
Thread.sleep(5000L);
// Clicking on the Hidden SubMenu
driver.findElement(By.Id("sbEle")).click();
Hey thank you so much for the help. I solved this by
w.keyPressNative(String.valueOf(KeyEvent.VK_B));
w.keyPressNative(String.valueOf(KeyEvent.VK_A));
w.keyPressNative(String.valueOf(KeyEvent.VK_N));
w.keyPressNative("40"); // down arrow key
Thread.sleep(4000);
w.keyPressNative("10"); //Enter key
In the below scenario what I did is...(dropdwon is in the table)
clicked the cell
get all cell values from the table(probably the list will be configured as table or list .. here it is table)
traverse through all the cells.
click on the required value based on the cell value.
driver.findElement(By.id("ms__id3")).click();
WebElement table = driver.findElement(By.className("combo-list-table"));
allRows = table.findElements(By.tagName("tr"));
for (WebElement row : allRows)
{
cells = row.findElements(By.tagName("td"));
for (WebElement cell : cells)
{
if(cell.getAttribute("text").equalsIgnoreCase("Business"))
{
cell.click();
}
}
}
Hope this will help...:)
i am new to Htmlunit and trying to extract data from a website http://capitaline.com/new/index.asp. I have logged into the website successfully. When we log into website there are three frames.
One on the top to search for the company(like ACC ltd.) for which we are extracting data.
2nd frame has a tree which provide links to various data we want to look at.
3rd frame has the resulted data outcome on the basis of link you clicked in frame.
I managed to get the frame i need below:
HtmlPage companyAtGlanceTopWindow =(HtmlPage)companyAtGlanceLink.click().getEnclosingWindow().getTopWindow().getEnclosedPage();
HtmlPage companyAtGlanceFrame = (HtmlPage)companyAtGlanceTopWindow.getFrameByName("mid2").getEnclosedPage();
System.out.println(companyAtGlanceFrame.toString()); // This line returns the frame URL as i can see in my browser.
Output of print statement is
HtmlPage(http://capitaline.com/user/companyatglance.asp?id=CGO&cocode=6)#1194282974
Now i want my code to navigate down to the table inside this frame and for that i am using getByXPath() but it gives me nullPointerException. Here is the code for that.
HtmlTable companyGlanceTable1 = companyAtGlanceFrame.getFirstByXPath("/html/body/table[4]/tbody/tr/td/table/tbody/tr/td[1]/table");
My XPath for the current webpage(after i clicked the link)from which i am trying to extract table is seems correct, as it is copied from chrome element inspect. Please suggest some way to extract the table. I have done this type of extraction before but there i had id of table so, i used it.
Here is the HTML code for the table in the webpage.
<table width="100%" class = "tablelines" border = "0" >
I want to know that can you see the inner contents of each iframes in console (print asXml()), are they nested iframes?
well try this
List<WebWindow> windows = webClient.getWebWindows();
for(WebWindow w : windows){
HtmlPage hpage = (HtmlPage) w.getEnclosedPage();
System.out.println(hpage.asXml());
}
once you can see the contents,
HtmlPage hpage = (HtmlPage)webClient.getWebWindowByName(some_name).getEnclosedPage();
then using xpath grab your table contents(make sure your xpath is correct). It will work.(worked for me)
Thank you RDD for your feedback.
I solved the problem. Actually issue was not with the frame but with the XPath provided by chrome.
XPath Provided by chrome is:
/html/body/**table[4]**/tbody/tr/td/table/tbody/tr/td[1]/table
But the XPath worked for me is:
/html/body/**table[3]**/tbody/tr/td/table/tbody/tr/td[1]/table
It seems as, XPath provided by chrome has some glitch when there is a table within the path(Or may be some bug in htmlunit itself). I did many experiments and found that chrome always gives ../../table[row+1]/.. as XPath, while working XPath for htmlunit is ../../table[row]/..
SO, this code is working fine for me
HtmlTable companyGlanceTable1 = companyAtGlanceFrame.getFirstByXPath("/html/body/table[3]/tbody/tr/td/table/tbody/tr/td[1]/table");
I am trying to interact with the Nike shoe online shop, login and then select a shoe size from the list and then press add to cart button from Selenium's Java WebDriver:
http://store.nike.com/us/en_us/pd/air-max-2014-running-shoe/pid-830258/pgid-774364
First of all I cannot seem to find the correct <li> element and select it - and need some advise on how to do it.
I am finding my code does not work for selecting a shoe size : pastebin.com/6K1RpPKL (as guided by the kind user on the first response.
The element type in li is not select. Use following code instead, it will work fine.
WebElement shoeSizes = driver.findElement(By.xpath("//div[contains(#class,'exp-pdp-size-container')]/a"));
shoeSizes.click(); // Expanded
String shoeSize = "8.5";
WebElement shoeSizeSel = driver.findElement(By.xpath("//li[text()='"+shoeSize+"']"));
shoeSizeSel.click(); // Size selected
driver.findElement(By.xpath("//div[#class='exp-pdp-save-container']/button")).click(); // Added to cart
As far as advice goes, you should first learn the basics like identifying elements, using locators before asking these kind of question. Go through these: Selenium Docs, Mozilla Blogs. Many such resources are available on web.
First off, you should get away from the IDE if you are wanting more robust test-writing like flash. For your login issue, this is simple.
Using the getting started with selenium framework your test would look like:
#Config(url="http://store.nike.com/us/en_us/pd/air-max-2014-running-shoe/pid-830258/pgid-774364")
public class NikeTest extends AutomationTest {
#Test
public void testNike() {
click (By.cssSelector("div.login.nav-section > a"))
.setText(By.cssSelector("form[name='login-form] input[name='email']"), "<My Username>")
.setText(By.cssSelector("form[name='login-form] input[name='password']"), "<My Password>")
.click (By.cssSelector("form[name='login-form] button.exp-login-submit")
// now we're logged in.
// let's select a size of shoe.
.click (By.cssSelector("div.exp-pdp-size-and-quantity-container > a.exp-pdp-size-dropdown") // now it's expanded.
.selectOptionByText(By.cssSelector("select[name='skuAndSize']"), "10.5") // you can replace 10.5 with whatever option you need.
}
}
Those are some CSS selectors you can use. Also per your Flash thing, i think you're out of luck buddy.. I hadn't heard of any very successful solution with automating flash.
One key thing here:
Make sure you know what element is receiving the click. Selenium IDE doesn't do a great job determining WHAT exact element is receiving the click. My guess is that it was trying either the <div> or <li> when it's the <a> that actually makes the dropdown come down.