Jsoup - Select the value from href attribute - java

The html code (not from my website, so I cant change it) looks like this:
<div id="resulttable">
<div class="dirlist">
<div class="stationcol" style="width:428px;">
<div class="videoBody">
<div class="gridModule">
<div class="surrogate">
<div id="thumbnail105867" class="thumbnail">
<a class="playbutton clickabletitle" name="whatever" id="105867" title="Whatever" href="http://whatever.com?id=xxx"> Bla </a>
</div></div></div></div></div></div></div>
Here is my Code:
Document doc = Jsoup.parse(result);
Elements hrefs = doc.select("div.stationcol a[href]");
StringBuilder links = new StringBuilder();
for (Element href : hrefs) {
links.append(href.text());
}
String httplinks = links.toString();
System.out.println("TEST: " + httplinks);
The output looks like:
I/System.out(10451): Link1http://www.whatever.c...Link2http://www.test.c...
What I really need is an ArrayList that contains the Urls and maybe one separate ArrayList that contains the Titles.
Can anyone help me please?

Do you mean something like this?
ArrayList<String> titles = new ArrayList<String>();
ArrayList<String> urls = new ArrayList<String>();
Document doc = Jsoup.parse(result);
Elements links = doc.select("div.stationcol > a[href]");
for (Element e : links) {
titles.add(e.attr("title"));
urls.add(e.attr("href"));
}
System.out.println(titles);
System.out.println(urls);
This will output the contents of both ArrayLists in your sample code, e.g:
[Whatever]
[http://whatever.com?id=xxx]

Related

How to fetch data from ul li in android studio with jsoup

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.

How access to inner same classname div with different idname in HTML data using Jsoup in android

I'm trying to parse data from HTML.I need to get the all names from inner div class=vacancy-item which has different idnames.
Below please See the HTML code
<section class="home-vacancies" id="vacancy_wrapper">
<div class="home-block-title">job openings</div>
<div class="vacancy-filter">
...................
</div>
<div class="vacancy-wrapper">
<div class="vacancy-item" data-id="9120">
..............
</div>
<div class="vacancy-item" data-id="9119">
..................
</div>
<div class="vacancy-item" data-id="9118">
................................
</div>
<div class="vacancy-item" data-id="9117">
.............................
</div>
Here is my code:
Please help.
doc = Jsoup.connect("URL").get();
//title = doc.select(".page-content div:eq(3)");
title = doc.getElementsByClass("div[class=vacancy-wrapper]");
titleList.clear();
for (Element titles : title) {
String text = titles.getElementsB("vacancy-item").text();
titleList.add(text);
}
Thanks!
You can only query for a class attribute with getElementByClass, e.g. getElementByClass("vacancy-wrapper") would work.
You will also need a second loop to get each vacancy-items text as a separate element:
Elements title = doc.getElementsByClass("vacancy-wrapper");
for (Element titles : title) {
Elements items = titles.getElementsByClass("vacancy-item");
for (Element item : items) {
String text = item.text();
// process text
}
}
An other option would be to use Jsoup's select method:
Elements es = doc.select("div.vacancy-wrapper div.vacancy-item");
for (Element vi : es) {
String text = vi.text());
// process text
}
This would select all div elements with a class attribute vacancy-item that are under a div with a class attribute vacancy-wrapper.

Extract Data from HTML using JSoup

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.

Getting child elements using WebDriver

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"));

Jsoup parse HTML including span tags

I have a HTML with the following format
<article class="cik" id="100">
<a class="ci" href="/abc/1001/STUFF">
<img alt="Micky Mouse" src="/images/1001.jpg" />
<span class="mick vtEnabled"></span>
</a>
<div>
Micky Mouse
<span class="FP">$88.00</span> <span class="SP">$49.90</span>
</div>
</article>
In the above code the tag inside article has a span class="mick vtEnabled" with no lable. I want to check if this span tag with the class name specified is present within the article tag. How do i do that? I tried select("> a[href] > span.mick vtEnabled") and checked the size..it remains 0 for all the article tags irrespective if its set or not. any inputs?
Starting from individual article tags would be good:
final String test = "<article class=\"cik\" id=\"100\"><a class=\"ci\" href=\"/abc/1001/STUFF\"><img alt=\"Micky Mouse\" src=\"/images/1001.jpg\" /></a><div>Micky Mouse<span class=\"FP\">$88.00</span> <span class=\"SP\">$49.90</span></div></article>";
final Elements articles = Jsoup.parse(test).select("article");
for (final Element article : articles) {
final Elements articleImages = article.select("> a[href] > img[src]");
for (final Element image : articleImages) {
System.out.println(image.attr("src"));
}
final Elements articleLinks = article.select("> div > a[href]");
for (final Element link : articleLinks) {
System.out.println(link.attr("href"));
System.out.println(link.text());
}
final Elements articleFPSpans = article.select("> div > span.FP");
for (final Element span : articleFPSpans) {
System.out.println(span.text());
}
}
final Elements articleSPSpans = article.select("> div > span.SP");
for (final Element span : articleSPSpans) {
System.out.println(span.text());
}
}
This prints:
/images/1001.jpg
/abc/1001/STUFF
Micky Mouse
$88.00
$49.90

Categories

Resources