Reputation: 11
I have this html code, and I need to get the link
<div class="squaresContent narrow">
<input type="hidden" id="category_path" value="1_Komputery > Części i obudowy komputerowe > Dyski twarde" />
<div class="productItem first2Col first3Col first4Col first">
<a class="productItemContent withNames productsView" href='http://www.okazje.info.pl/km/komputery/samsung-ssd-850-evo-250gb-sata3-2-5-mz-75e250b-eu.html'>
I do next :
String ref = null;
for (Element el : doc.getElementsByClass("squaresContent narrow")) {
for (Element elem : el.getElementsByClass("productItem first2Col first3Col first4Col first")
.select("a")) {
ref = elem.attr("abs:href");
}
}
But it`s not work.
What should I do?
Upvotes: 0
Views: 600
Reputation: 11712
getElementsByClass
should be used only with ONE class name as argument. If you need multiple class names you can use the css selector syntax, where a class name is specified by .classname
, i.e. dot followed by the class name:
String ref = null;
for (Element el : doc.select(".squaresContent.narrow")) {
for (Element elem : el.select(".productItem.first2Col.first3Col.first4Col.first a")) {
ref = elem.attr("abs:href");
}
}
BTW: your loops run not very efficiently. In the case when more then one matching element is found in the outer or inner loop you overwrite the ref variable. A more elegant way of doing this might be:
String ref = null;
try{
Element aEl = doc.select(".squaresContent.narrow").last()
.select(".productItem.first2Col.first3Col.first4Col.first a").last();
ref = aEl.attr("abs:href");
}
catch (NullPointerException e){
e.printStackTrace();
}
You need the try catch because there might not be any matching a element and this results in a NPE.
Upvotes: 2