read subtext of an element - java

how can i read value of this xpath '/html/body/article/div[2]/div/div[1]/div[10]/div/div/text()[1]' in java?
findElement(By.xpath(xpath));
i can access item via chrome extention but in java it fails saying no element found. i can only access like this; '/html/body/article/div[2]/div/div[1]/div[10]/div/div' but it is not what i want.
for example for this site: https://www.milliyet.com.tr/siyaset/canikli-kararlilikla-yurumeye-devam-ediyoruz-6277692
i would like to get these items text value separately
/html/body/article/div[2]/div/div[1]/div[10]/div/div/text()[1]
/html/body/article/div[2]/div/div[1]/div[10]/div/div/span/span[1]/time
/html/body/article/div[2]/div/div[1]/div[10]/div/div/span/span[2]/time
thanks.

findElement () can only return the Web element which contains the text you may need. If you need the actual text within the element, you have to use getText() method. You will first need to find the element and use getText() method to retrieve the text.
WebElement myElement = findElement(By.xpath("/html/body/article/div[2]/div/div[1]/div[10]/div/div"));
System.out.println(myElement.getText());

Use relative XPath to fetch your data. You can use the 3 following XPath :
//div[#class='nd-article__info-block']
(//time[#datetime])[1]
(//time[#datetime])[2]
To extract the text, use getText() method :
string el1 = driver.FindElement(By.XPath("//div[#class='nd-article__info-block']")).getText();
string el2 = driver.FindElement(By.XPath("(//time[#datetime])[1]")).getText();
string el2 = driver.FindElement(By.XPath("(//time[#datetime])[2]")).getText();
You can also store the 3 results in a list with a single XPath expression :
//div[#class='nd-article__info-block']|//time[#datetime]
Code :
List<WebElement> list=driver.findElements(By.xpath("//div[#class='nd-article__info-block']|//time[#datetime]"));
List<String> els_text=new ArrayList<>();
for(int i=0; i<list.size(); i++){
els_text.add(list.get(i).getText());
System.out.println(list.get(i).getText());
}

Related

Selenium webdriver - Iterate, find webelement and then click on it - how can I do that?

I'd like to find the webelement that has as the visible text "7000118777", however I don't know how to exactly find it in the list and then click on it.
When I iterate it shows that the index is -1 and I get the error of "productList.get(-1);" - this is not the correct one.
public void findProductAndAddToCart(String product) {
List<WebElement> productList = SeleniumDriver.getDriver().findElements(By.className("bcom--txtBold"));
for (WebElement webElement : productList) {
String elements = (webElement.getAttribute("innerHTML"));
int indexOfProduct = elements.indexOf("7000118777");
System.out.println("Indeks produktu "+indexOfProduct);
}
productList.get(-1);
As you have not provided a link to url or screenshot of your html, this is what i understand from your question that you want to click on a element from a list where visible text is "7000118777". I also believe that you located the elements correct i.e., your productList. Please refer the below code (Replace myDriver with your WebDriver) :
List<WebElement> productList = myDriver.findElements(By.className("bcom--txtBold"));
for (int i=0; i< productList.size();i++) {
String element=productList.get(i).getText();
if(element.equals("7000118777"))
{
productList.get(i).click();
}
}

[Selenium][Java][PageObject] How to check if we have 'xyz' value ( of Web Element) on the list with values?

I have created a test that adds xyz1 , xyz2, xyz3 ....xyz(n) element , what is presented as a list on page. I need to be sure that among these names exists element titled " xyz3" (or titled different , what I will define)
My idea is to build list/ array /collection that will gather all values of web element and then I need to write a method that will looking for my defined "xyz3" among these values collected in list.
My web element:
#FindBy(how = How.XPATH, using = "//div[#id='_field']")
public List <WebElement> listOfNames;
My attempts in creating a list :
LList<WebElement> myElements = createEvalTemplateLocators.getListOfNames();
boolean temp1;
for(WebElement e : myElements) {
System.out.println(e.getText() + "");
}
for(WebElement e : myElements) {
temp1 = e.getText().contains("temp1");
if (temp1==true) System.out.println("hurray temp1 is on page ");
else {System.out.println("something gone wrong with temp1");}
}
RESULT IN CONSOLE:
I am not able to create better locator- more appropiate that will not 'take' element next to it...
Moreover I want to know if on the list exist 'temp1' one at least only, info message about each entity is not neccessary....
I don't have any better ideas for my test, in the future I would like to use asserts for this case..
I am beginner :( and I am learning on my own mostly, so could anybody help me with this case ?
( Greetings from Baltic Sea for All :))

Extract text from multiple xpath and assert text - Selenium/Java

I need to find the text in an element and assert whether it matches with my required result.
The thing is, there can be n number of element from 1-100 in the page. So I can't get the xpath of all those elements and then assert the text in it.
The xpath looks like this: (from the first element)
(//DIV[#class='issues-list-item clearfix'])[1]
(//DIV[#class='issues-list-item clearfix'])[2]
(//DIV[#class='issues-list-item clearfix'])[3]
(//DIV[#class='issues-list-item clearfix'])[4]
....
(//DIV[#class='issues-list-item clearfix'])[100]
How do I loop through these xpath and assert for my text?
I tried the below method after referring few articles and it really did not help.
private static WebElement element = null;
private static List<WebElement> elements = null;
public WebElement test() throws Exception {
elements = driver.findElements(By.xpath("(//DIV[#class='issues-list-item clearfix'])[1]"));
for (WebElement element : elements) {
List<WebElement> TE = element.findElements(By.xpath("(//DIV[#class='issues-list-item clearfix'])[1]"));
if (TE.size() > 0) {
String myText = TE.get(0).getText();
if (myText.contains("High")) {
return element;
}
}
}
return null;
You can try this :
public List<WebElement> test() throws Exception {
List<WebElement> TE = new ArrayList<WebElement>();
elements = driver.findElements(By.xpath("(//DIV[#class='issues-list-item clearfix'])"));
for (WebElement element : elements) {
if(element.getText().contains("High")) {
TE.add(element);
}
}
return TE;
}
Note that , it will return a list web element which contains High as text.
The more efficient way to do this is to add your check for "High" to the locator. That way you don't have to loop through all the elements to find only the ones you want. Your locator does all that work for you and more quickly. There's also a lot less code.
public List<WebElement> test() throws Exception {
return driver.findElements(By.xpath("(//DIV[#class='issues-list-item clearfix'][contains(.,'High')])"));
}
There are a number of ways you can verify that the desired element is found. One way would be to use a TestNG Assert like
Assert.assertTrue(test().size() > 0, "Verify an element containing 'High' was found.");
//DIV[#class='issues-list-item clearfix'])[1] your query is wrong. The [1] at the end means that it will select oinly teh first item from all the items matching the query before, aka you will only compare against the first one. The second query you won't need, neitehr the if checking for size (optionally before the for loop)

Java Selenium webdriver filling list webelement manually

first of all:
I want to fill a List manually with element.add();
Because the elements of the page I am working with is just showing a specific range of elements, I can't just load all elements in a List<WebElement>.
That's why I want to do functions to check if an element exists in my List, if it doesn't exists there I will add it.
I want to know if there is a way to iterate specific elements like element.next();
Here is the xpath I am getting my elements:
###.findElement(By.xpath(".//a[starts-with(#href, '/p/')]"));
You ca use following snippet to fulfill your requirement
public boolean isDropdownOptionExists(String optionToBeVerified, By optionWhereToBeVerified) {
boolean isOptionFound = false;
Select optionsInDropDown = new Select(driver.findElement(optionWhereToBeVerified));
List<WebElement> availableOptions = optionsInDropDown.getOptions();
for(WebElement option: availableOptions) {
if(option.getText().equals(optionToBeVerified)) {
isOptionFound = true;
break;
}
}
return isOptionFound;
}

Jsoup not matching tags without certain attributes?

I have a function that, given a div element, will find all img elements within it.
The only problem is that only the first 3 are being selected. The only difference between the first 3 and the rest is the inclusion of attributes (class and alt)
Document doc = Jsoup.connect("http://www.dhgate.com/wholesale/kitchen-fixtures/c019034002-1.html").get();
Elements elements = doc.select("div.prolist");
for (Element e : elements) {
String img[] = getImagesSrc(e, 1);
}
....
protected String[] getImagesSrc(Element e, int numOfImages) {
String src[];
src = new String[numOfImages];
int i = 0;
Elements imgElements = e.select("img[src]");
for (Element o : imgElements) {
System.out.println("html = " + o.outerHtml());
src[i++] = o.attr("src");
}
return src;
}
Some example div element (These are what gets passed to the function)
<div class="prolist">
<img class="folder" alt="Folder" src="folder.jpg"/>
</div>
<div...
...div>
<div class="prolist">
<img src="folder.jpg"/>
</div>
Shouldn't I be getting all images regardless of the sttributes?
I have tested the code using the same HTML structure from the website and from localhost. The code DOES work on locahost but NOT on the website (www.dhgate.com)
SOLVED - The site was using lazyload plugin so the HTML in the inspector was reading different from what Jsoup was. In my case I had to include 'a' tags that had [class~=lazyload]
The program does get the source of all img tags inside a div element with class prolist. But you should take into account some issue that may occur depending on you complete program.
for (Element e : elements) {
String img[] = getImagesSrc(e, 1);
}
In the first loop the img array is overwritten on each iteration. So if you have multiple div elements with class prolist, the img tag array of each will overwrite the other. If you want to get the entire img or all div tags change the getImagesSrc() method argument to Elements and pass doc.select("div.prolist") directly.
The second argument for getImagesSrc() method is used to initialze the array. So in case if we have more than one img tags it will result in an ArrayOutOfBoundException. The number of image tags are indetermisnistic. So you should use a List in this case. If you want an array you can later make an array out of the list. For e.g
protected String[] getImagesSrc(Element e) {
List<String> imgSources = new ArrayList<String>();
Elements imgElements = e.select("img[src]");
for (Element o : imgElements) {
imgSources.add(o.attr("src"));
}
return imgSources.toArray(new String[imgSources.size()]);
}
Also note that since you are slecting img like e.select("img[src]");, it'll only return img tags that has an src attribute.

Categories

Resources