How to get text from this html page with jsoup?

2020-02-07 06:37发布

问题:

I am using this code to retreive the text in the main article on this page.

public class HtmlparserExampleActivity extends Activity {
String outputtext;
  TagFindingVisitor visitor;
  Parser parser = null;
private static final String TAG = "TVGuide";



TextView outputTextView;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    outputTextView = (TextView)findViewById(R.id.outputTextView);
    String id = "main-article-content";
    Document doc = null;

    try {
        doc = Jsoup.connect("http://movies.ign.com/articles/100/1002569p1.html").get();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Log.i("DOC", doc.toString().toString());
    Elements elementsHtml = doc.getElementsByTag(id);  
    String[] temp1 = new String[99];    
    int i =0;
    for(Element element: elementsHtml)
    {

        temp1[1] = element.text();
        i++;
        outputTextView.setText(temp1[1]);

The problem is nothing is showing up in the textview. None of the text that i am trying to retreive is showing up. The Log.i is showing up with the segments in the debug log. So i know its connecting successfully. Just dont know why im not getting any text in the textview.

回答1:

Here's a simplified extract of relevance from your question:

Document doc = Jsoup.connect("http://movies.ign.com/articles/100/1002569p1.html").get();
Elements elementsHtml = doc.getElementsByTag("main-article-content");  
// ...

You're making a fundamental mistake here. There are no HTML tags like <main-article-content> in the document. However, there's a <div id="main-article-content">. According the CSS selector overview about halfway this Jsoup cookbook, you should be using #id selector.

Document doc = Jsoup.connect("http://movies.ign.com/articles/100/1002569p1.html").get();
Element mainArticleContent = doc.select("#main-article-content").first();  
// ...