所以我正在學習如何使用XPath和HtmlCleaner來解析HTML,但我有一個問題。這是代碼:使用XPath導致問題
public class ScheudeleWithDesign extends Activity {
static final String urlToParse = "https://www.easistent.com/urniki/263/razredi/18221";
static final String xpathTableContents = "//div[@id='text11']";
TextView tw1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scheudele_with_design);
tw1 = (TextView) findViewById(R.id.urnikText);
String value = "";
value = new getScheudele().execute().toString();
tw1.setText(value);
}//End of onCreate
private class getScheudele extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
String stats = null;
//cleaner properties
HtmlCleaner cleaner = new HtmlCleaner();
CleanerProperties props = cleaner.getProperties();
props.setAllowHtmlInsideAttributes(false);
props.setAllowMultiWordAttributes(false);
props.setRecognizeUnicodeChars(true);
props.setOmitComments(true);
URL url;
try {
url = new URL(urlToParse);
TagNode root = cleaner.clean(url);
Object[] node = root.evaluateXPath(xpathTableContents);
//Vzemi podatke če najdeš element
if (node.length > 0) {
TagNode resultNode = (TagNode)node[10];
stats = resultNode.getText().toString();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XPatherException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return stats;
}
}
所以我很明顯試圖解析某些數據並將其設置爲textview。這不,雖然工作,結果是完全錯誤的:
我的猜測是,這個問題是在這裏的XPath:
static final String xpathTableContents = "//div[@id='text11']";
我從來沒有使用XPath之前,所以我幾乎可以肯定我搞砸了那部分。 This is the site我想從中解析數據。這段代碼應該只有一個表格元素供初學者使用,一旦我知道如何去做,我將解析整個表格。
''// div [@ id ='text11']「'XPath is t試圖選擇任何'id'屬性等於'text11'的div元素,但是在被引用的HTML頁面中沒有這樣的div元素。 (有很多div元素,其class屬性設置爲'text11'。)如果您提供了一個特定的數據示例,您希望從鏈接的HTML頁面中選擇數據,我們可以幫助您製作XPath。 – kjhughes
@kjhughes我仍在嘗試學習XPath,但我總是遇到一個問題,學習了一些我一無所知的新東西。你能給我一個關於如何選擇任何表格內容的例子嗎?只需向我展示一個XPath代碼,以獲取您需要的任何表格內容,以便以某種方式「獲取結構」。我非常感謝,謝謝! – Guy