android html download and parse error
Question
I am trying to download the html file using the ul of the page. I am using Jsoup. This is my code:
TextView ptext = (TextView) findViewById(R.id.pagetext);
Document doc = null;
try {
doc = (Document) Jsoup.connect(mNewLinkUrl).get();
} catch (IOException e) {
Log.d(TAG, e.toString());
e.printStackTrace();
}
NodeList nl = doc.getElementsByTagName("meta");
Element meta = (Element) nl.item(0);
String title = meta.attr("title");
ptext.append("\n" + mNewLinkUrl);
When running it, I am getting an error saying attr is not defined for the type element. What have I done wrong? Pardon me if this seems trivial.
Solution
Ensure that Element
refers to org.jsoup.nodes.Element
, not something else. Verify your imports. Also ensure that Document
refers to org.jsoup.nodes.Document
. It does namely not have a getElementsByTagName()
method. Jsoup doesn't utilize any of the org.w3c.dom
API.
Here's a complete example with the correct imports:
package com.stackoverflow.q4720189;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
public class Test {
public static void main(String[] args) throws Exception {
Document document = Jsoup.connect("http://example.com").get();
Element firstMeta = document.select("meta").first();
String title = firstMeta.attr("title");
// ...
}
}
OTHER TIPS
As I understand, Element here is org.w3c.dom.Element
. Then use meta.getAttribute()
instead of attr
. Element class simply doesn't have such method.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow