Reputation: 263
I want to extract data from a Web site, using Jsoup. The data are in a table.
HTML code:
<table><tr><td><a href="......">Pop.Density</a></td>
<td>123</td></tr></table>
I want to print:
zip code...(taken from a text file): 123
I have the following exception:
Exception in thread "main" java.lang.NullPointerException
Any help would be appreciated. Thank you!
This is my code:
String s = br.readLine();
String str="http://www.bestplaces.net/people/zip-code/illinois/"+s;
org.jsoup.Connection conn = Jsoup.connect(str);
conn.timeout(1800000);
Document doc = conn.get();
for (Element table : doc.select("table"))
{
for (Element row : table.select("tr"))
{
Elements tds = row.select("td");
if (tds.size() > 1)
{
Element link = tds.get(0).select("a").first();
String linkText = link.text();
if (link.text().contains("Pop.Density"))
System.out.println(s+","+tds.get(1).text());
}
}
}
UPDATE: If I modify the last if():
if (tds.get(0).select("a").text().contains("Pop.Density"))
I do not have any exceptions, but no output either.
Upvotes: 1
Views: 1979
Reputation: 34367
Assuming the shared html is not the real one being used, I think its throwing the exception when first TD doesn't have <a>
tag. I think you need to update
if (tds.size() > 1)
as
if (tds.size() > 1 && tds.get(0).select("a") != null
&& tds.get(0).select("a").first() ! null)
If this is not the case, sharing the line number of NullPointerException
origin can help better finding the solution.
Upvotes: 1