2

我正在尝试构建 HTML 解析器,但出现两个错误:

Type mismatch: cannot convert from Element to Elements  MainActivity.java   /test/src/com/example/test  line 55 Java Problem
first cannot be resolved or is not a field  MainActivity.java   /test/src/com/example/test  line 54 Java Problem

线上:

Elements th = doc.select("tr").first;
Elements firstTh = th.select("th").first();

有谁知道为什么会发生这种情况或我能做些什么来解决这个问题?这是我第一次构建解析器,所以我不确定我到底做错了什么。

package com.example.test;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {

    TextView tv;
    final String URL = "http://exampleurl.com";
String tr;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = (TextView) findViewById(R.id.TextView01);
        new MyTask().execute(URL);
    }

    private class MyTask extends AsyncTask<String, Void, String> {
        ProgressDialog prog;
        String title = "";

        @Override
        protected void onPreExecute() {
            prog = new ProgressDialog(MainActivity.this);
            prog.setMessage("Loading....");
            prog.show();
        }

        @Override
        protected String doInBackground(String... params) {
            try {
                Document doc = Jsoup.connect(params[0]).get();
                Elements tableElement = doc.select(".datagrid");
                Elements th = doc.select("tr").first;
                Elements firstTh = th.select("th").first();
                title = firstTh.text();
        }   catch (IOException e) {
                e.printStackTrace();
            }
            return title;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            prog.dismiss();
            tv.setText(result);
        }
    }
}
4

1 回答 1

2

编译器错误是问题的一个很好的指标 -first返回一个Element对象而不是Elements

Elements th = doc.select("tr").first;

应该

Element th = doc.select("tr").first();

也换

Elements firstTh = th.select("th").first();

Element firstTh = th.select("th").first();
于 2013-10-04T16:54:50.133 回答