[英]Using XPath causing problems
所以我正在学习如何使用XPath和HtmlCleaner来解析HTML,但是我遇到了问题。 这是代码:
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。 但是,这不起作用,结果是完全错误的:
com.whizzapps.stpsurniki.ScheudeleWithDesign$getScheudele@421a7d90
我的猜测是问题出在这里的XPath中:
static final String xpathTableContents = "//div[@id='text11']";
我以前从未使用过XPath,因此几乎可以肯定我已经搞砸了。 这是我尝试从中解析数据的站点 。 这段代码对于初学者来说应该只有一个表元素,一旦我知道如何做,就将解析整个表。
我的猜测是问题出在这里的XPath中:
static final String xpathTableContents = "//div[@id='text11']";
正如我在评论中提到的那样, //div[@id='text11']
XPath试图选择id
属性等于text11
任何div
元素,但是在引用的HTML页面中没有这样的div元素。
您能否给我一个示例,说明如何选择任何表内容? 只需为我显示所需的任何表内容的XPath代码,即可以某种方式“获取结构”。
使用您引用的HTML页面选择包含“ 2. ura”的div,例如:
//*[@id="seznam_ur_teden"]/table/tbody/tr[3]/td[1]/div[1]
要仅在此处选择文本,
//*[@id="seznam_ur_teden"]/table/tbody/tr[3]/td[1]/div[1]/text()
要选择整个祖先表:
//*[@id="seznam_ur_teden"]/table
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.