How can we pick html elements value using web driver - selenium

Hi i want to get value of html element using web driver how can i get it?I am explaining the scenario as below. I have a span element as below with value between the starting and closing tag .How can i get it?
<span id="foo">
some value
</span>

You have to use the webElement.getText() for that.
I worte a small unit test for you:
public class TestGetText
{
#Test
public void shouldReadSomevalue()
{
final WebDriver webDriver = new HtmlUnitDriver();
webDriver.get("http://s2server.de/stackoverflow/11719445.html");
final WebElement webElement = webDriver.findElement(By.id("foo"));
final String text = webElement.getText();
assertEquals("some value", text);
}
}

Try below solution -
String test = driver.findElement(By.id("lbHome")).getText();
System.out.println(test);

Try locating the element using XPath instead of ID, then using either
driver.findElement(By.xpath(“xpath for your lbl“)).getText()
or
String st = driver.findElement(By.xpath(“xpath to your lbl“)).getAttribute(“value”);
Source : SeleniumWiki

Related

How to pass dynamic value into xpath in selenium, java?

I have a website, where i open contract and get the unique contractId. Then, i need to go to other page and search this id in table with pagination. I wrote code which goes to next page if this requesid(it's a link) is not found and if it exist, it just opens this requestId. But there is a problem with initialization of webelement where i'm trying add dynamic value. Selenium gives error below and i have no idea how to solve it
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//span[#class='link__text' and text()='222254']/../../..//input"}
(Session info: chrome=89.0.4389.72)
contractId is the variable where i store dynamic value that changes every test run. This is how the code looks like:
csecp.waitForElementVisibility(csecp.getContractStatusEmergencyChangeHeader());
int totalPages = Integer.parseInt(csecp.getTotalPagesString().getText());
for(int i = 0; i < totalPages; i++) {
csecp.sleep(500);
if (**csecp.prepareWebElementWithDynamicXpath(csecp.getContractDynamicValue(),contractId).isDisplayed()**) {
csecp.prepareWebElementWithDynamicXpath(csecp.getContractDynamicValue(),contractId).click();
csecp.waitForElementVisibility(csecp.getConfirmAMLApprovalButton());
csecp.getConfirmAMLApprovalButton().click();
break;
}
csecp.waitForElementVisibility(csecp.getNextPageButton());
csecp.getNextPageButton().click();
}
This is how i'm trying to pass dynamic valueinto xpath
private String contractDynamicValue = "//span[#class='link__text' and text()='xxxxx']/../../..//input";
public WebElement prepareWebElementWithDynamicXpath (String xpathValue, String substitutionValue ) {
return getWebDriver().findElement(By.xpath(xpathValue.replace("xxxxx", substitutionValue)));
}
You can define and use this XPath locator as following:
String contractDynamicValue = "//span[#class='link__text' and text()='%s']/../../..//input";
public WebElement prepareWebElementWithDynamicXpath (String xpathTemplate, String substitutionValue ) {
String xpath = String.format(xpathTemplate,substitutionValue);
return getWebDriver().findElement(By.xpath(xpath));
}
See the xpath that you are using is
//span[#class='link__text' and text()='xxxxx']/../../..//input
and if you wanna make xxxxx as dynamic, you could do following :-
string sub_value = "222254";
//span[#class='link__text' and text()='"+sub_value+"']/../../..//input
It's always the best solution to get element by text and the following element. For dynamic elements, you can use XPath like
//div[.='Dummy_text']/following::span[text()='test_text']
You can see some tutorials from here
https://www.guru99.com/xpath-selenium.html

Element present fails due to iframe issue for getting image src using Selenium WebDriver

As we know iframe can be counted using frameslist but that doesn't work for me and gives blank output although frame count gives me count as 2. I'm using Selenium WebDriver and Java.
Basically I want to get img source's data-mce-src starts with cid and dfsrc ends with # according to below screenshot.
I tried :
public static final String imageAttachment="css=img[data-mce-src^='cid']&&[data-mce-src$='#']";
which works fine using sIsElementPresent in selenium 1.0 but it fails in webdriver using findElement. In fact it doesn't identify iframe itself.
Expected:
css=img[data-mce-src^='cid']&&[data-mce-src$='#'] element present?
Code:
WebElement we = null;
List <WebElement> framesList = webDriver().findElements(By.tagName("iframe"));
for (WebElement frame:framesList){
System.out.println(frame.getText()); // returns nothing
}
int listSize = framesList.size();
webDriver().findElement(By.xpath("//iframe"));
System.out.println(listSize);
Also tried:
webDriver().switchTo().frame(webDriver().findElements(By.tagName("iframe"));
we = webDriver().findElement(By.cssSelector("html body div img"));
System.out.println(we.getAttribute("src")); // returns nothing
You should try as below :-
webDriver().switchTo().frame("Editor1_body_ifr");
we = webDriver().findElement(By.cssSelector("body#tinymce img"));
System.out.println(we.getAttribute("src"));
try {
webDriver().switchTo().frame("Editor1_body_ifr");
we = webDriver().findElement(By.cssSelector("html body img"));
System.out.println(we.getAttribute("src"));
System.out.println(we.getAttribute("data-mce-src"));
System.out.println(we.getAttribute("dfsrc"));
} finally {
webDriver.switchTo().defaultContent();
}

selenium span link li not working

I am new to selenium. I am practicing to write a test case on http://www.countdown.tfl.gov.uk. Below are the steps I followed:
a) I opened the browser to selenium Web Driver
b) Found the search text Box and enter H32 and clicked on search button to selenium.
Till this part it works fine.
Now on the page I am actually getting two records on the left side of the page under the search. I am actually trying to click on the first one i.e. "Towards Southall,Townhall" link. Nothing is happening.
Below is my code:
public class CountdownTest {
#Test
public void tflpageOpen(){
WebDriver driver = openWebDriver();
searchforBus(driver,"H32");
selectrouteDirection(driver)
}
//open the countdowntfl page
private WebDriver openWebDriver(){
WebDriver driver = WebDriverFactory.getWebDriver("FireFox");
driver.get("http://www.countdown.tfl.gov.uk");
return driver;
}
private void searchforBus(WebDriver driver,String search){
WebElement searchBox = driver.findElement(By.xpath("//input[#id='initialSearchField']"));
searchBox.sendKeys(search);
WebElement searchButton = driver.findElement(By.xpath("//button[#id='ext-gen35']"));
searchButton.click();
}
private void selectrouteDirection(WebDriver driver){
WebElement towardssouthallLink= driver.findElement(By.xpath("//span[#id='ext-gen165']']"));
((WebElement) towardssouthallLink).click();
}
}
Please help me.
Thanks.
Since you are getting NoSuchElement Exception now, you may try the following code with the usage of WebDriver explicit wait.
WebDriverWait wait = new WebDriverWait(driver, 15);
WebElement towardssouthallLink = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("(//*[#id='route-search']//li/span)[1]")));
towardssouthallLink.click();
Or WebDriver implicit wait
WebDriver driver = WebDriverFactory.getWebDriver("FireFox");
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://www.countdown.tfl.gov.uk");
Tips:
The search results need some time to be retrieved, so please use Explicit wait or Implicit wait.
Don't use locators like span[#id='ext-gen165'], they are ExtJs auto generated.
In this case, css selector can also be used: #route-search li:nth-of-type(1) > span
You aren't calling selectrouteDirection.
You probably want:
#Test
public void tflpageOpen(){
WebDriver driver = openWebDriver();
searchforBus(driver,"H32");
selectrouteDirection(driver);
}
You also don't need to cast here:
((WebElement) towardssouthallLink).click();
It's already a WebElement anyway.
I found that id for those links are dynamically generated. ids are of the form 'ext-genXXX' where XXX is number which is dynamically generated hence varies each time.
Actually, you should try with linkText:
For 'Towards Southall, Town Hall'
driver.findElement(By.linkText("Towards Southall, Town Hall")).click
For 'Towards Hounslow, Bus Station'
driver.findElement(By.linkText("Towards Hounslow, Bus Station")).click
Here is a logic:
Get all elements which have id starts with 'ext-gen' & iterate over it & click on link with matching text. Following is Ruby code(sorry, I don't know Java well):
links = driver.find_elements(:xpath, "//span[starts-with(#id, 'ext-gen')]")
links.each do |link|
if link.text == "Towards Southall, Town Hall"
link.click
break
end
end

Webdriver returns error for textarea.sendKeys(text)

I am using Webdriver 2.25.0 and Firefox 14
I have the following textarea:
<textarea id="source-text" placeholder="Start typing your text" style="resize: none; overflow: hidden;"></textarea>
I am identifying this text area in my HomePage object like this:
#FindBy(how = How.CSS, using = "div.myclass textarea")
public WebElement columnLeftTextarea;
What i want to do is simply type some text inside this textarea, by using the following code
homePage.columnLeftTextarea.sendKeys("some text");
This is returning the following error:
Type mismatch Can't assign non-array value to an array
The textarea is correctly defined as when i run
homePage.columnLeftTextarea.getAttribute("placeholder")
i get the correct text
I even tried to do start the browser by setting the capabilities to tnable native events:
FirefoxProfile ffProfile = new FirefoxProfile(new File(generalPropertiesTestObject.getFirefox_profile_template_location()));
ffProfile.setEnableNativeEvents(true);
FirefoxDriver ffd = new FirefoxDriver(ffProfile);
capabilities = ffd.getCapabilities();
But still i am getting the same error. Does anyone have any idea about it?
Try firstly focusing into textarea. I did it using the following code:
driver.findElement(By.id("source-text")).clear();
driver.findElement(By.id("source-text")).sendKeys("some text");
and it seems to work just fine.
You need change this code:
#FindBy(how = How.CSS, using = "div.myclass textarea")
public WebElement columnLeftTextarea;
on this:
#FindBy(how = How.ID, using = "source-text")
public WebElement columnLeftTextarea;
Firstly, it works more faster, because search by ID works more faster than search by CSS.
Secondly, ID changes is not so much time as CSS.

Get value of DIV - WebDriver (Selenium)

I want to get the value of div using webdriver and not Selenium
For example :
<div class="headerbande">BIENVENUE</div>
Is there any method in webdriver to get "BIENVENUE" using class name ?
Thanks in advance.
With java you would write:
WebElement element = webdriver.findElement(By.className("headerbande"));
Take a look at Introducing the Selenium-WebDriver API by Example for examples in other languages.
Thanks Volkerk, I found the solution via your post
WebElement webElement = driver.findElement(By.cssSelector("headerband"));
webElement.getText();
in ruby, you can locate the element using
css selector
web_element = driver.find_element(css: 'div.headerbande')
class
web_element = driver.find_element(class: 'headerbande')
id
# if your element's id is 'headerbande'
web_element = driver.find_element(id: 'headerbande')
It is also possible to get value/text by using xpath as below:
WebElement webElement = driver.findElement(By.xpath("//div[#class='headerbande']"));
webElement.getText();
OR,
You can get text/value by using css Selector as below:
WebElement webElement = driver.findElement(By.cssSelector("div.headerbande"));
webElement.getText();
you can use:
driver.findElementByClassName("headerbande").getText();