iT邦幫忙

0

android studio 擷取網頁中的指定內容問題?

  • 分享至 

  • xImage

以下程式碼跑完,查詢的時候,只會出現"查無資料,請輸入正確股號",想請問是哪裡出問題,還是要加什麼程式??

謝謝。

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private TextView text;
    private EditText edit;
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = (TextView) findViewById(R.id.textView);
        edit = (EditText) findViewById(R.id.editText);
        btn = (Button) findViewById(R.id.button);
    }

    public void search(View view) {
        btn.setClickable(false);
        String editext = edit.getText().toString();
        if (editext.matches("[0-9]{1}[0-9]{3}"))
            new stackpricedown().execute(editext);
        else {
            text.setText("請輸入正確股號格式");
            btn.setClickable(true);
        }
    }

    private class stackpricedown extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            text.setText("資料下載中");
        }

        @Override
        protected String doInBackground(String... strings) {
            String result="",htmlInf;
            try {
                URL url = new URL("http://www.tse.com.tw/zh/stockSearch/stockSearch");
                ConnectWeb connectStock = new ConnectWeb(url);
                htmlInf = connectStock.postData("stkNo",strings[0]);
                if(htmlInf.contains("<!-- 終止上市 -->")){
                    return "終止上市";
                }
                else if (htmlInf.contains("各檔權證即時行情及基本資料")) {
                    result = getstockdata(htmlInf);
                }else
                    result="查無資料\n請輸入正確股號";
            }catch(MalformedURLException e) {
                return e.getMessage();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            btn.setClickable(true);
            super.onPostExecute(s);
            text.setText(s);
        }
    }

    private String getstockdata(String htmlInf) {
        String result="";
        Pattern ptn =Pattern.compile("table");
        Matcher mch = ptn.matcher(htmlInf);
        String subs="";
        int start=0,end=0;
        while(mch.find()){
            start = mch.start();
            subs=htmlInf.substring(end,start);
            if(subs.contains("開盤競價基準")){
                break;
            }
            end = mch.end();
        }
        result = subs.split("<td>")[2].replace("</td>","");
        return result;
    }
}

ConnectWeb.java

public class ConnectWeb {
    private URL url;

    public ConnectWeb(URL url){
        this.url=url;
    }

    public String postData(String key,String value) {
        String htmlInf="";
        try{
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            try {
                urlConnection.setChunkedStreamingMode(0);//不知道資料長度時呼叫,避免緩存耗盡
                urlConnection.setRequestMethod("POST");//預設是GET 用POST要改
                urlConnection.setDoOutput(true);//default id false
                urlConnection.setDoInput(true);//default is true

                String outputData = keyAndValue(key,value);
                writeHtmldata(urlConnection,outputData);
                htmlInf = readHtmlStream(urlConnection);

            } finally {
                urlConnection.disconnect();
            }
        } catch (MalformedURLException e) {
            return "Exception:" + e.getMessage();
        } catch (IOException e) {
            return "Exception:" + e.getMessage();
        }
        return htmlInf;
    }

    private String keyAndValue(String key,String value){
        StringBuilder outputDataBuilder = new StringBuilder();
        outputDataBuilder.append(key);
        outputDataBuilder.append("=");
        outputDataBuilder.append(value);
        return outputDataBuilder.toString();
    }

    private void writeHtmldata(HttpURLConnection urlConnection,String outputData) throws IOException {
        OutputStream os = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));//bufferwriter 處理的資料是字串 自動在字元跟位元組之間作轉換
        try {
            writer.write(outputData);
            writer.flush();
        }finally {
            writer.close();
            os.close();
        }
    }

    private String readHtmlStream(HttpURLConnection urlConnection) throws IOException {
        InputStream is = new BufferedInputStream(urlConnection.getInputStream());//讀進來時不需做位元組與字元轉換 不需要用reader
        OutputStream bo = new ByteArrayOutputStream();
        try {
            int i = is.read();
            while (i != -1) {
                bo.write(i);
                i = is.read();
            }
        } finally {
            bo.close();
            is.close();
        }
        return bo.toString();
    }
}

APP畫面:
https://ithelp.ithome.com.tw/upload/images/20190729/201193797LEPtnWPqV.png


教學來源:https://foolcodefun.github.io/blog/android/2017/09/22/Android-%E7%B6%B2%E9%A0%81%E8%B3%87%E6%96%99%E6%93%B7%E5%8F%96.html

小魚 iT邦大師 1 級 ‧ 2019-07-29 14:56:16 檢舉
這是兩年前的教學,
說不定網頁已經改版了,
你應該要先去研究那個網頁.
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

2
dragonH
iT邦超人 5 級 ‧ 2019-07-29 15:09:21

網頁實測我實測過沒問題

post stkNo = 1101

也確定可以

且網站文字也有

各檔權證即時行情及基本資料

所以有問題的應該是你的 code

先把

htmlInf = connectStock.postData("stkNo",strings[0]);

的 strings[0] 想辦法印出來看長怎樣

在把 htmlInf 印出來看取到的資料是什麼

也要注意 log 是否有什麼錯誤

搞不好你可能因為權限的問題

根本沒發 post

Judy_Lee iT邦新手 5 級 ‧ 2019-07-29 21:20:09 檢舉

好的,我試試,謝謝。

0
海綿寶寶
iT邦大神 1 級 ‧ 2019-07-30 11:47:09

執行程式出現錯誤訊息Exception:Cleartext HTTP traffic to www.tse.com.tw not permitted
只要在 AndroidManifest.xml 裡加上

<uses-permission android:name="android.permission.INTERNET" />
以及
<application ..
  ...
  android:usesCleartextTraffic="true"
  ...
  />

即可解決此一錯誤訊息

然而接著出現結果為

<html>
    <head><title>302 Found</title></head>
    <body bgcolor="white">
    <center><h1>302 Found</h1></center>
    <hr><center>nginx</center>
    </body>
</html>

我就不繼續 debug 了

Judy_Lee iT邦新手 5 級 ‧ 2019-07-30 21:17:21 檢舉

好的,謝謝

我要發表回答

立即登入回答