Selecting a drop down option - selenium

I'm simulating a mobile phone browser and tryng to select a dropdown item.
I'm using a css selector to find the combobox, when I check that css selector in the developers tool is found but not in my code
List<WebElement> linkElements = driver.findElements(By
.cssSelector(".show-deals-wrapper select"));
for (WebElement element : linkElements) {
if (element.isDisplayed()
&& ("Pay Monthly").equals(element.getText())) {
element.click();
break;
}
}
The web is https://www.o2.co.uk/shop in mobile version.
I'm really new in Selenium, learning bit a bit. Sorry if the question is so easy.
Many thanks in advance.
Regards

You can use javascript to make the element visible first. then do your job as it is and finally make that element invisible again. see the code portion below:
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("document.getElementById('elementID').style.display='block'");
Select select = new Select(driver.findElement(elementID));
select.selectByIndex(pos);
js.executeScript("document.getElementById('elementID').style.display='none'");
I think this will help you.

This is how I handle selects with webdriver. I hope this helps. Also I am using python
Select(driver.find_element_by_css_selector('.show-deals-wrapper.select')).select_by_visible_text("Pay Monthly")

u can aslo do like below:
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,300)", "");
driver.findElement(By.id("dataFilterSelectSelectBoxItArrowContainer")).click();
List<WebElement> linkElements = driver.findElements(By
.cssSelector(" #dataFilterSelectSelectBoxItOptions>li>a"));
System.out.println("size is "+linkElements.size());
for (WebElement element : linkElements) {
System.out.println("size is "+element.getText());
if (("ur text").equals(element.getText())) {
element.click();
break;
}
}
this will click on what sort tariff u want.

Related

Selenium how to click/ access an a tag with a href that has a javascript function

I have searched but havent found something similar to what Im trying to do. I'm using java by the way, I'm trying to click/access an a tag with selenium. The issue is that I'm not sure how to go about it. There seems to be a function/event that I need to set off but not quite sure how to. I tried a few ways as get text and clicking but I knew that wasn't going to work. Also I seen there are ways of using JavascriptExecutor but not sure how to use it for my case. I will post the tag below and alsothe function signature, that might help. If theres a similar question please post the link.
<a name="DERIVED_SSS_SCL_SSS_ENRL_CART$276$" id="DERIVED_SSS_SCL_SSS_ENRL_CART$276$" ptlinktgt="pt_peoplecode" tabindex="203" onclick="javascript:cancelBubble(event);" href="javascript:submitAction_win0(document.win0,'DERIVED_SSS_SCL_SSS_ENRL_CART$276$');" class="SSSHYPERLINKBOLDSMALL">Enrollment Shopping Cart</a>
the signature
function submitAction_win0(form, id, event)
You don't need any JS. Just use this xpath:
"//a[contains(#onclick,'javascript:cancelBubble(event);')]"
Be sure the element is clickable, see
import org.openqa.selenium.support.ui.ExpectedConditions;
for the case of more matches:
List<WebElement> elements = driver.findElements(By.xpath("//a[contains(#onclick,'javascript:cancelBubble(event);')]"));
int elementIndex = 0; // 0 to get first of the 33 mathes, 32 to get the last one
WebElement element = elements.get(elementIndex);
element.click();
EDIT:
You should use WebDriverWait to avoid NoSuchElementException this way the driver will wait until the element is clickable... it will wait up to 10 seconds you can tell it to wait more if needed...
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.partialLinkText("Student Center")));
element.click();
Using click():
WebElement element = driver.findElement(By.cssSelector("a[class='SSSHYPERLINKBOLDSMALL']"));
element.click();
Using JavascriptExecutor (Not recommended):
WebElement element = driver.findElement(By.cssSelector("a[class='SSSHYPERLINKBOLDSMALL']"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);
You can use other locators too... like linkText:
WebElement element = driver.findElement(By.linkText("Enrollment Shopping Cart"));
Or partialLinkText:
WebElement element = driver.findElement(By.partialLinkText("Shopping Cart"));

How to perform a scroll in a drop down list to hidden element?

How to perform a scroll in a drop down list with that format with selenium, appium ?
I'm using tag name to identify elements, <md-option .../> are the items in the drop down list.
Here is my html code :
I have solved it by this way :
// Create instance of Javascript executor
JavascriptExecutor je = (JavascriptExecutor) driver;
//Identify the WebElement which will appear after scrolling down
WebElement element = driver.findElement(By.tagName("...."));
// now execute query which actually will scroll until that element is not appeared on page.
je.executeScript("arguments[0].scrollIntoView(true);",element);
Try following code.
browser.executeScript('window.scrollTo(0,0);').then(function () {
page.saveButton.click();
})
Hope this helps. :)

FindallElements using className does not work but using the same code with xpath works

For practice I was working on code and faced a very strange problem. I am trying to find the list of all elements using className. When I check the list size it returned me 0 but the same class when used with xpath works. My code is below
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.localbanya.com/home/search?searchKeyword=dove");
driver.findElement(By.xpath("//*[#class='ms-choice']")).click();
Thread.sleep(2000);
driver.findElement(By.xpath("//*[#class='ms-drop bottom']//li[4]/label")).click();
driver.findElement(By.cssSelector(".proceed-button.button")).click();
Thread.sleep(1000);
List<WebElement> prList = driver.findElements(By.xpath("//*[#class='prName']"));
// This particular code does not work but same class name used above works
//----Interesting not working
//List<WebElement> prList = driver.findElements(By.className(".prName"));
System.out.println(prList.size());
for (WebElement web : prList)
{
System.out.println(web.getText());
}
//driver.close();
}
List<WebElement> prList = driver.findElements(By.className("prName"));
It will work, no need to use . while you are using By.className. . is required when you use css selector.

How to locate search links in google in Selenium for testing

I am trying to search Google for Selenium, then run down the list of links by clicking each one, printing the page title, then navigating back.
List<WebElement> linkElements = driver.findElements( **<insert code here>** );
for(WebElement elem: linkElements)
{
String text = elem.getText();
driver.findElement(By.linkText(text)).click();
System.out.println("Title of link\t:\t" + driver.getTitle());
driver.navigate().back();
}
To find the elements, I have tried By.tagName("a") which doesn't work because it gets ALL the links, not just the search ones. Using Firebug, I see that each search link has a class of r used on the header h3, and the a tag nested inside it.
See the following:
<h3 class="r">
<a href="/url sa=t&rct=j&q=selenium&source=web&cd=1&cad=rja&ved=0CC8QFjAA&url=http%3A%2F%2Fseleniumhq.org%2F&ei=y4eNUYiIGuS7iwL-r4DADA&usg=AFQjCNHCelhj_BWssRX2H0HZCcPqhgBrRg&sig2=WBhmm65gCH7RQxIv9vgrug&bvm=bv.46340616,d.cGE" onmousedown="return rwt(this,'','','','1','AFQjCNHCelhj_BWssRX2H0HZCcPqhgBrRg','WBhmm65gCH7RQxIv9vgrug','0CC8QFjAA','','',event)"><em>Selenium</em> - Web Browser Automation
</a></h3>
What code can I insert to make this work?
You have a lot of solution for doing it. There's mine. You keep your way like
// You get all links in a list
List<WebElement> linkElements = driver.findElements(By.xpath("//h3/a"));
// for each element(link) you click() on it
for(WebElement elem: linkElements)
{
elem.click();
// i suggest to put a wait right there
System.out.println("Title of link\t:\t" + driver.getTitle());
driver.navigate().back();
}
i don't know why you were trying to complicate with getText() etc.
Try below New Code
WebDriver driver;
driver = new FirefoxDriver();
driver.get("http://www.google.com");
driver.findElement(By.id("gbqfq")).sendKeys("Selenium");
Thread.sleep(1500L);
driver.findElement(By.id("gbqfb")).click();
Thread.sleep(1500L);
List<WebElement> linkElements = driver.findElements(By.xpath("//h3[#class='r']/a"));
for(int i=0;i<=linkElements.size();i++)
{
String text = linkElements.get(i).getText();
driver.findElement(By.linkText(text)).click();
Thread.sleep(2000L);
System.out.println("Title of link\t:\t" + driver.getTitle());
Thread.sleep(2000L);
driver.navigate().back();
linkElements = driver.findElements(By.xpath("//h3[#class='r']/a"));
}
try searching for this selector:
'.g:nth-child('+clickPosition+') h3.r a'
where "clickPosition" is the SERP result array key. Careful though, google now implements an "onmousedown" event that will change the href attribute to their redirect.

Scroll Element into View with Selenium

Is there any way in either Selenium 1.x or 2.x to scroll the browser window so that a particular element identified by an XPath is in view of the browser? There is a focus method in Selenium, but it does not seem to physically scroll the view in FireFox. Does anyone have any suggestions on how to do this?
The reason I need this is I'm testing the click of an element on the page. Unfortunately the event doesn't seem to work unless the element is visible. I don't have control of the code that fires when the element is clicked, so I can't debug or make modifications to it, so, easiest solution is to scroll the item into view.
Have tried many things with respect to scroll, but the below code has provided better results.
This will scroll until the element is in view:
WebElement element = driver.findElement(By.id("id_of_element"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(500);
//do anything you want with the element
You can use the org.openqa.selenium.interactions.Actions class to move to an element.
Java:
WebElement element = driver.findElement(By.id("my-id"));
Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.perform();
Python:
from selenium.webdriver.common.action_chains import ActionChains
ActionChains(driver).move_to_element(driver.sl.find_element_by_id('my-id')).perform()
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("javascript:window.scrollBy(250,350)");
You may want to try this.
If you want to scroll on the Firefox window using the Selenium webdriver, one of the ways is to use JavaScript in the Java code. The JavaScript code to scroll down (to bottom of the web page) is as follows:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollTo(0, Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, document.documentElement.clientHeight));");
Targeting any element and sending down keys (or up/left/right) seems to work also. I know this is a bit of a hack, but I'm not really into the idea of using JavaScript to solve the scrolling problem either.
For example:
WebElement.sendKeys(Keys.DOWN);
In Selenium we need to take the help of a JavaScript executor to scroll to an element or scroll the page:
je.executeScript("arguments[0].scrollIntoView(true);", element);
In the above statement element is the exact element where we need to scroll. I tried the above code, and it worked for me.
I have a complete post and video on this:
http://learn-automation.com/how-to-scroll-into-view-in-selenium-webdriver/
webElement = driver.findElement(By.xpath("bla-bla-bla"));
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", webElement);
For more examples, go here. All in Russian, but Java code is cross-cultural :)
I found that the bounding rect of my element was not correct, leading to the browser scrolling well off the screen. However, the following code works rather well for me:
private void scrollToElement(WebElement webElement) throws Exception {
((JavascriptExecutor)webDriver).executeScript("arguments[0].scrollIntoViewIfNeeded()", webElement);
Thread.sleep(500);
}
You can use this code snippet to scroll:
C#
var element = Driver.FindElement(By.Id("element-id"));
Actions actions = new Actions(Driver);
actions.MoveToElement(element).Perform();
There you have it
This worked for me:
IWebElement element = driver.FindElements(getApplicationObject(currentObjectName, currentObjectType, currentObjectUniqueId))[0];
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", element);
Use the driver to send keys like the pagedown or downarrow key to bring the element into view. I know it's too simple a solution and might not be applicable in all cases.
From my experience, Selenium Webdriver doesn't auto scroll to an element on click when there are more than one scrollable section on the page (which is quite common).
I am using Ruby, and for my AUT, I had to monkey patch the click method as follows;
class Element
#
# Alias the original click method to use later on
#
alias_method :base_click, :click
# Override the base click method to scroll into view if the element is not visible
# and then retry click
#
def click
begin
base_click
rescue Selenium::WebDriver::Error::ElementNotVisibleError
location_once_scrolled_into_view
base_click
end
end
The 'location_once_scrolled_into_view' method is an existing method on WebElement class.
I apreciate you may not be using Ruby but it should give you some ideas.
The Ruby script for scrolling an element into view is as below.
$driver.execute_script("arguments[0].scrollIntoView(true);", element)
sleep(3)
element.click
Selenium 2 tries to scroll to the element and then click on it. This is because Selenium 2 will not interact with an element unless it thinks that it is visible.
Scrolling to the element happens implicitly so you just need to find the item and then work with it.
Sometimes I also faced the problem of scrolling with Selenium. So I used javaScriptExecuter to achieve this.
For scrolling down:
WebDriver driver = new ChromeDriver();
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("window.scrollBy(0, 250)", "");
Or, also
js.executeScript("scroll(0, 250);");
For scrolling up:
js.executeScript("window.scrollBy(0,-250)", "");
Or,
js.executeScript("scroll(0, -250);");
This is a repeated solution with JavaScript, but with an added waiting for element.
Otherwise ElementNotVisibleException may appear if some action on the element is being done.
this.executeJavaScriptFunction("arguments[0].scrollIntoView(true);", elementToBeViewable);
WebDriverWait wait = new WebDriverWait(getDriver(), 5);
wait.until(ExpectedConditions.visibilityOf(elementToBeViewable));
I have used this way for scrolling the element and click:
List<WebElement> image = state.getDriver().findElements(By.xpath("//*[contains(#src,'image/plus_btn.jpg')]"));
for (WebElement clickimg : image)
{
((JavascriptExecutor) state.getDriver()).executeScript("arguments[0].scrollIntoView(false);", clickimg);
clickimg.click();
}
def scrollToElement(element: WebElement) = {
val location = element.getLocation
driver.asInstanceOf[JavascriptExecutor].executeScript(s"window.scrollTo(${location.getX},${location.getY});")
}
Something that worked for me was to use the Browser.MoveMouseToElement method on an element at the bottom of the browser window. Miraculously it worked in Internet Explorer, Firefox, and Chrome.
I chose this over the JavaScript injection technique just because it felt less hacky.
You may want to visit page Scroll Web elements and Web page- Selenium WebDriver using Javascript:
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
FirefoxDriver ff = new FirefoxDriver();
ff.get("http://toolsqa.com");
Thread.sleep(5000);
ff.executeScript("document.getElementById('text-8').scrollIntoView(true);");
}
If you think other answers were too hacky, this one is too, but there is no JavaScript injection involved.
When the button is off the screen, it breaks and scrolls to it, so retry it... ¯\_(ツ)_/¯
try
{
element.Click();
}
catch {
element.Click();
}
In most of the situation for scrolling this code will work.
WebElement element = driver.findElement(By.xpath("xpath_Of_Element"));
js.executeScript("arguments[0].click();",element);
JAVA
Try scroll to element utilize x y position, and use JavascriptExecutor with this is argument: "window.scrollBy(x, y)".
Following import:
import org.openqa.selenium.WebElement;
import org.openqa.selenium.JavascriptExecutor;
First you need get x y location the element.
//initialize element
WebElement element = driver.findElement(By.id("..."));
//get position
int x = element.getLocation().getX();
int y = element.getLocation().getY();
//scroll to x y
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(" +x +", " +y +")");
I am not sure if the question is still relevant but after referring to scrollIntoView documentation from https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView.
The easiest solution would be
executor.executeScript("arguments[0].scrollIntoView({block: \"center\",inline: \"center\",behavior: \"smooth\"});",element);
This scrolls the element into center of the page.
Javascript
The solustion is simple:
const element = await driver.findElement(...)
await driver.executeScript("arguments[0].scrollIntoView(true);", element)
await driver.sleep(500);
The default behavior of Selenium us to scroll so the element is barely in view at the top of the viewport. Also, not all browsers have the exact same behavior. This is very dis-satisfying. If you record videos of your browser tests, like I do, what you want is for the element to scroll into view and be vertically centered.
Here is my solution for Java:
public List<String> getBoundedRectangleOfElement(WebElement we)
{
JavascriptExecutor je = (JavascriptExecutor) driver;
List<String> bounds = (ArrayList<String>) je.executeScript(
"var rect = arguments[0].getBoundingClientRect();" +
"return [ '' + parseInt(rect.left), '' + parseInt(rect.top), '' + parseInt(rect.width), '' + parseInt(rect.height) ]", we);
System.out.println("top: " + bounds.get(1));
return bounds;
}
And then, to scroll, you call it like this:
public void scrollToElementAndCenterVertically(WebElement we)
{
List<String> bounds = getBoundedRectangleOfElement(we);
Long totalInnerPageHeight = getViewPortHeight(driver);
JavascriptExecutor je = (JavascriptExecutor) driver;
je.executeScript("window.scrollTo(0, " + (Integer.parseInt(bounds.get(1)) - (totalInnerPageHeight/2)) + ");");
je.executeScript("arguments[0].style.outline = \"thick solid #0000FF\";", we);
}
I've been doing testing with ADF components and you have to have a separate command for scrolling if lazy loading is used. If the object is not loaded and you attempt to find it using Selenium, Selenium will throw an element-not-found exception.
If nothing works, try this before clicking:
public void mouseHoverJScript(WebElement HoverElement) {
String mouseOverScript = "if(document.createEvent){var evObj = document.createEvent('MouseEvents');evObj.initEvent('mouseover', true, false); arguments[0].dispatchEvent(evObj);} else if(document.createEventObject) { arguments[0].fireEvent('onmouseover');}";
((JavascriptExecutor) driver).executeScript(mouseOverScript, HoverElement);
}
In Java we can scroll by using JavaScript, like in the following code:
driver.getEval("var elm = window.document.getElementById('scrollDiv'); if (elm.scrollHeight > elm.clientHeight){elm.scrollTop = elm.scrollHeight;}");
You can assign a desired value to the "elm.scrollTop" variable.
A solution is:
public void javascriptclick(String element)
{
WebElement webElement = driver.findElement(By.xpath(element));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", webElement);
System.out.println("javascriptclick" + " " + element);
}