Hi I could not get the text from html I wanna get this text This is a test text
<div class="rehou">
<span class="tlid-t t">
<span title="" class="">This is a test text</span>
</span>
<span class="tlid-t-v" style="" role="button"></span>
</div>
My java:
Document doc = Jsoup.connect(url).get();
Elements ele= doc.select("span.tlid-t t");
textass = ele.text();
The span has the two different classes tlid-t and t. So if you want to use both classes in your select you should use span.tlid-t.t instead of span.tlid-t t.
Elements ele = doc.select("span.tlid-t.t");
String textass = ele.text();
System.out.println(textass);
Which would print This is a test text.
But this will select the outer span! If the html gets changed the content of textass will be also changing. If you only want to select the text of the inner span you should use span.tlid-t.t span.
Elements ele = doc.select("span.tlid-t.t span");
String textass = ele.text();
System.out.println(textass);
This will also print This is a test text.
Related
Can anyone help me to find out the list of child tagnames using reference of parent tagname.
In a table I have list of rows and columns which means each row has 14 columns and each column has list of inner tags like span, span, input. Now I need to find the list of items under column td[11] for which I have written the below code:
element=driver.findElement(shopviewtableid);
items=element.findElements(shopviewrow);
if(items.size()>0) {
for(WebElement ele:items) {
columnvalues=ele.findElements(shopviewcolumn);
for(WebElement item:columnvalues) {
System.out.println("Inside Tag name of each column"+item..toString());
In the above code I am passing table id in shopviewtable id and tagname tr for shopviewrow and xpath //td[11] for shopviewcolumn. Now after fetching the td[11] for each row again I am fetching the list of items under td[11]
for(WebElement item:columnvalues) {
System.out.println("Inside Tag name of each column"+item..toString());" .
Here under td[11] I have three items with tagname as span,span,input. PFA screenshot How do I get name of these tags from the list[enter image description here]
Tried using item.getTagname() for each item but it displays td as tagname and not the name of the element inside the td[11].
It would be great if anyone could help me on this issue.
Here is my Html structure:
<td role="gridcell" style="width: 11%;" class="jqnoDetails">
<span id="detailsForm:j_id_5q:0:minQuantity" class="hidden">1</span>
<span id="detailsForm:j_id_5q:0:incQuantity" class="hidden">1</span>
<span id="detailsForm:j_id_5q:0:originalQuantity" class="hidden">1.0000</span>
<input id="detailsForm:j_id_5q:0:quantity" name="detailsForm:j_id_5q:0:quantity" type="text" value="1" min="0" inc="1" onblur="PrimeFaces.bcn(this,event,[function(event){handleQuantityChanged(this); updatePrice($(this), 11.23);},function(event){jsf.ajax.request('detailsForm:j_id_5q:0:quantity',event,{execute:'#this ',render:'#this ','CLIENT_BEHAVIOR_RENDERING_MODE':'OBSTRUSIVE','javax.faces.behavior.event':'blur'})}])" style="width: 85%;" aria-required="true" class="ui-inputfield ui-inputtext ui-widget ui-state-default ui-corner-all jqQuantityInput textCenter" role="textbox" aria-disabled="false" aria-readonly="false">
</td>
I am assuming that you have the mechanism to find the cell using iteration as shown. Now try to get all child elements of particular grid cell using XPath like this -
List<WebElement> childElements =item.findElements(By.xpath(".//child::*"));
//try even (".//*") as XPath to get the child elements
once you have a list of elements, you can iterate using for loop to get required tag or another data getAttribute method of WebElement.
Please find the below code to get the tag names of each element inside a cell.
element=driver.findElement(shopviewtableid);
items=element.findElements(shopviewrow);
if(items.size()>0) {
for(WebElement ele:items) {
columnvalues=ele.findElements(shopviewcolumn);
for(WebElement item:columnvalues) {
System.out.println("Inside Tag name of each column");
insideElements=item.findElements(By.xpath("//*");
for(WebElement ele:insideElements)
{
System.out.println("Inside Element tag:"+ ele.getTagName();
}
}
I am trying to get Product 1 and Product 2 but I cant get it help please
I am using jsoup and volley
<ul id="searched-products">
<li>
<div class="gd-col navUnitContainer1 gu4">
<div class="product_name">
<a>Prodict 1</a>
</div>
</div>
</li>
<li>
<div class="gd-col navUnitContainer1 gu4">
<div class="product_name">
<a>Prodict 2</a>
</div>
</div>
</li>
</ul>
I have tried this
Elements itemElements = doc.select("ul#searched-products li");
but its not selecting "li".I have also tried this
Elements itemElements = doc.select("ul#searched-products"); //this line works
Element e1 = itemElements.get(i);
e1.select("li"); or item.getElementsByTag("li");
still no good...
There are hundreds of li so I cant do this
doc.select("li");
Kindly suggest something
Like this:
public class JsoupList {
public static void main(String[] brawwwr){
String html = "<ul id=\"searched-products\">" +
"<li>" +
"<div class=\"gd-col navUnitContainer1 gu4\">" +
"<div class=\"product_name\">" +
"<a>Prodict 1</a>" +
"</div>" +
"</div>" +
"</li>" +
"<li>" +
"<div class=\"gd-col navUnitContainer1 gu4\">" +
"<div class=\"product_name\">"+
"<a>Prodict 2</a>" +
"</div>" +
"</div>" +
"</li>" +
"</ul>";
Document doc = Jsoup.parse(html);
Elements itemElements = doc.select("ul#searched-products li");
for(Element elem : itemElements){
System.out.println(elem.select("div div a").text());
}
}
}
Will return
Prodict 1
Prodict 2
You can imagine repetitive code inside tags like a little page of its own.
regards
Try this code.
Elements itemElements = doc.select("ul#searched-products");
itemElements = itemElements.select("li");
for(Element ele : itemElements){
String text = ele.text();
System.out.println(text); //this will return Prodict 1 and Prodict 2
}
// or u can try by getting all the a
for(Element ele : itemElements){
String text = ele.select("a").first().text();
System.out.println(text); //this will also return Prodict 1 and Prodict 2
}
To exclude <li> or <a> tags outside the list, you need to restrict the selector to match only inside the list. The best would be to use the ID (#searched-products). Then do not select <li> or <a> tags from the doc, but from the selected <ul>element.
You can get your text with any of the following selectors (not a complete list):
#searched-products li a
#searched-products a
#searched-products .product_name a
#searched-products .product_name
Even the last one is okay, since you need only the text, and div.product_name contains only the <a> tag.
for(Element e: doc.select("#searched-products .product_name")) {
String t = e.text(); // Prodict N
}
By the way, your original approach with selecting <li> tags inside ul#searched-products should have worked. If that doesn't return anything, the case might be that the list is generated dynamically on that page. You can test it easily by printing out the HTML that Jsoup has (doc.html() or doc.select('#searched-products').html()).
If really that's the case, Jsoup is not the right tool for you. I suggest you to use Selenium with possibly a headless browser (HtmlUnit or PhantomJS). They can return and even interact with dynamically created elements, so maybe other parts of your crawl process can be simplified.
I am writing a script to extract data from a HTML Document. Here is a part of the document.
<div class="info">
<div id="info_box" class="inf_clear">
<div id="restaurant_info_box_left">
<table id="rest_logo">
<tr>
<td>
<a itemprop="url" title="XYZ" href="XYZ.com">
<img src="/files/logo/26721.jpg" alt="XYZ" title="XYZ" width="100" />
</a>
</td>
</tr>
</table>
<h1 id="Name"><a class="fn org url" rel="Order Online" href="XYZ.com" title="XYZ" itemprop="name">XYZ</a></h1>
<div class="rest_data" itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">
<span itemprop="telephone">(305) 535-1379</span> | <b>
<span itemprop="streetAddress">1755 Alton Rd</span>,
<span itemprop="addressLocality">Miami Beach</span>,
<span itemprop="addressRegion">FL</span>
<span itemprop="postalCode">33139</span></b>
</div>
<div class="geo">
<span class="latitude" title="25.792588"></span>
<span class="longitude" title="-80.141214"></span>
</div>
<div class="rest_data">Estimated delivery time: <b>45-60 min</b></div>
</div>
</div>
I am using Jsoup and not quite sure how to achieve this.
There are many div tags in the document and I try to match with their unique attribute.
Say for div tag with class attribute value as "info"
Elements divs = doc.select("div");
for (Element div : divs) {
String divClass = div.attr("class").toString();
if (divClass.equalsIgnoreCase("rest_info")) {
}
If matched, I have to get the table with id "rest_logo" inside that divtag.
When doc.select("table") is used, it looks like the parser searches the entire document.
What I need to achieve is, if the div tag attribute is matched, I need to fetch the elements and attributes inside the matched div tag.
Expected Output:
Name : XYZ
telephone:(305) 535-1379
streetAddress:1755 Alton Rd
addressLocality:Miami Beach
addressRegion:FL
postalCode:33139
latitude:25.792588
longitude:-80.141214
Estimated delivery time:45-60 min
Any Ideas?
for (Element e : doc.select("div.info")) {
System.out.println("Name: " + e.select("a.fn").text());
System.out.println("telephone: " + e.select("span[itemprop=telephone]").text());
System.out.println("streetAddress: " + e.select("span[itemprop=streetAddress]").text());
// .....
}
Here's how I would do it:
Document doc = Jsoup. parse(myHtml);
Elements elements = doc.select("div.info")
.select(”a[itemprop=url], span[itemprop=telephone], span[itemprop=streetAddress], span[itemprop=addressLocality], span[itemprop=addressRegion], span[itemprop=postalCode], span.longitude, span.latitude”);
elements.add(doc.select("div.info > div.rest_data").last());
for (Element e:elements) {
if (e.hasAttr("itemprop”)) {
System.out.println(e.attr("itemprop") + e.text());
}
if (e.hasAttr("itemprop”) && e.attr("itemprop").equals ("url")) {
System.out.println("name: " + e.attr("title"));
}
if (e.attr("class").equals("longitude") || e.attr("class").equals("latitude")) {
System.out. println(e.attr("class") + e.attr("title"));
}
if (e.attr("class").equals("rest_data")) {
System.out.println(e.text());
}
}
(Note: I wrote this on my phone, so untested, but it should work, may also contain typos)
A bit of explanation: First get all the desired elements via doc.select(...), and then extract the desired data from each one.
Let me know if it works.
Probably the main thing to realise is that an element with an id can be selected directly - no need to loop through a collection of elements searching for it.
I've not used JSoup and my Java is very rusty but here goes ...
// 1. Select elements from document
Element container = doc.select("#restaurant_info_box_left"); // find element in document with id="restaurant_info_box_left"
Element h1 = container.select("h1"); // find h1 element in container
Elements restData = container.select(".rest_data"); //find all divs in container with class="rest_data"
Element restData_0 = restData.get(0); // find first rest_data div
Element restData_1 = restData.get(1); // find second rest_data div
Elements restData_0_spans = restData_0.select("span"); // find first rest_data div's spans
Elements geos = container.select(".geo"); // find all divs in container with class="geo"
Element geo = geos.get(0); // find first .geo div
Elements geo_spans = geo.select("span"); // find first .geo div's spans
// 2. Compose output
// h1 text
String text = "Name: " + h1.text();
// output text >>>
// restData_0_spans text
for (Element span : restData_0_spans) {
String text = span.attr("itemprop").toString() + ": " + span.text();
// output text >>>
}
// geo data
for (Element span : geo_spans) {
String text = span.attr("class").toString() + ": " + span.attr("title").toString();
// output text >>>
}
// restData_1 text
String text = restData_1.text();
// output text >>>
For someone used to JavaScript/jQuery, this all seems very laboured. With luck it may simplify somewhat.
Hello I am using HtmlUnit library and I need to get some href attribute from an a tag, inside some div:
<div class="threadpostedin td alt">
<p>Forum:<br>
<a href="programming/website-development/"
title="Website Development">Website
Development</a></p>
</div>
This div is located inside a <li> which is located inside a <ol>
to get the ol I did this:
HtmlOrderedList l = (HtmlOrderedList) this.page.getElementById("searchbits");
The html:
<ol class="searchbits" id="searchbits" start="1">
Now from the div I posted, I need to get the href "programming/website-development/", but I am not sure how to do this. Yes the div has a class name, but if I do
for (DomElement ele : l.getChildElements()) {
System.out.println(ele.getByXPath("//div[#class='threadpostedin td alt']").size());
break;
}
it will print 15, because overall there are 15 lists in the ol, in each list there is one div with class threadpostedin td alt. What I need to do, is the the exact div with class threadpostedin td alt in the DomElement I got from the iteration, and not get the list of all divs with that class.
Is there a way to do this with HtmlUnit?
I assume you have more links than one to make it more detailed.
HtmlElement element = page.getByXPath("//div[#class='threadpostedin td alt']").get(0);
DomNodeList<DomNode> nodes = element.querySelectorAll("a");
for(DomNode a : nodes) {
if(a.getAttributes().getNamedItem("href") !=null) {
String href = page.getFullyQualifiedUrl(a.getAttributes().getNamedItem("href").getNodeValue()).toString().toLowerCase();
String baseUrl = page.getBaseURL().toString();
}
}
I've got the following HTML code:
<div class="ui-selectmenu-menu" style="z-index: 1; top: 251px; left: 37px;">
<ul class="ui-widget ui-widget-content ui-selectmenu-menu-dropdown ui-corner-bottom" aria-hidden="true" role="listbox" aria-labelledby="gwt-uid-191-button" id="gwt-uid-191-menu" style="width: 270px; height: auto;" aria-disabled="false" aria-activedescendant="ui-selectmenu-item-999">
<li role="presentation" class="ui-selectmenu-item-selected">
All Applications</li>
<li role="presentation" class="">
Option Alpha</li>
<li role="presentation" class="ui-corner-bottom">
Option Beta</li>
</ul>
</div>
...
<div class="ui-selectmenu-menu"...>...</div>
I'm able to get the WebElement for ui-selectmenu-menu like this (there are many on the page; hence, the use of findElements) :
List<WebElement> dropdowns = driver.findElements(By.className("ui-selectmenu-menu"));
And the ul below it like this:
WebElement ddChild = dropdowns.get(0).findElement(By.className("ui-selectmenu-menu-dropdown"));
I'm even able to grab all the li under the ddChild like this:
List<WebElement> ddOpts = ddChild.findElements(By.xpath("//*[#id='gwt-uid-191-menu']/li[*]"));
But the problem that I can't seem to figure out how to grab the text-value of the <a href="#nogo"... tag under each li element.
I'd like to be able to loop through all the ddOpts and grab the <a href="#nogo"... text values and save them to an ArrayList<String>.
So, for example, my first ArrayList<String> value would contain All Applications, then Option Alpha, then Option Beta, and then jump to the next ul element from the next dropdowns and do the whole process again, all while adding to the ArrayList<String>.
I'm sure its a simple solution but I've got limited experience with Selenium WebDriver.
Thanks!
PS: Is there a simple way to grab the child of a WebElement?
List<WebElement> ddOpts = ddChild.findElements(By.xpath("//*[#id='gwt-uid-191-menu']/li/a"));
ArrayList<String> links = new ArrayList<String>();
for(WebElement we : ddOpts) {
links.add(we.getText();
}
To extract the href attribute of the WebElement (referring to the anchor tag <a> in this example, do this:
List<WebElement> ddOpts = ddChild.findElements(By.xpath("//*[#id='gwt-uid-191-menu']/li/a"));
ArrayList<String> links = new ArrayList<String>();
for(WebElement we : ddOpts) {
// ADD all the href attribute strings to the list
links.add(we.getAttribute("href"));
}
This may also solve your problem:
List<WebElement> dropdowns = driver.findElements(By.className("x-combo-list"));
WebElement ddChild = dropdowns.get(0).findElement(By.className("x-combo-list-inner"));
List<WebElement> ddOpts = ddChild.findElements(By.xpath("//*[#id=\"x-auto-98\"]/div[4]"));
for(WebElement we:ddOpts){
System.out.println(we.getText());
if(we.getText().contains("ROLE_MANAGER")){
we.sendKeys("ROLE_MANAGER");
we.click();
break;
}
}
the below code will select the OptionAlpha in the dropdown of the above HTML code
driver.findElement(By.xpath("//*[#class='ui-selectmenu-menu')).click();
driver.findElement(By.xpath("//*[#class='ui-widget ui-widget-content ui-selectmenu-menu-dropdown ui-corner-bottom']//**[text()='Option Alpha']")).click();
Please try the below code to get all the links in the <a href
List<WebElement> allLis = driver.findElements(By.xpath("//*[#id='gwt-uid-191-menu']/li/a");
// Looping through above list using for-each loop
for(WebElement eachLi : allLis) {
System.out.println(eachLi.getText());
}
Hope this helps.
href="#nogo" is same for all the anchor tags, so it might create ambiguity in selecting the item by the method
dropdowns.findelement(By.linktext("#nogo"));