[英]Taking an webpage element with Jsoup in AsyncTask in a fragment (Android Newbie)
我是Java和Android的新手,所以需要您的帮助。 我已经在我的应用程序中实现了JSoup,以便从网页中获取此消息并在textview中显示(我正在片段中操作,但在这种情况下,我认为它与标准活动相同)。
<body marginwidth="0" marginheight="0">
<h1></h1>
<p class="testoprezzo">0.5516 </p>
</body>
我只需要0.5516
我不知道该怎么做。 你能帮助我吗? 这是我已经编写的代码: class fetcher extends AsyncTask<Void,Void, Void> { @Override protected Void doInBackground(Void... arg0) { try { String value = "https://mywebpage.net/"; Document document = Jsoup.connect(value).followRedirects(false).timeout(30000).get(); Element p= document.select ("p.testoprezzo").first(); ((Globals)getApplication()).setValore(p.text()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); TextView valore = findViewById(R.id.textView4); valore.setText(((Globals)getApplication()).getValore()); } }
先感谢您!
尽量使用限制性最强的选择器,以免获得不相关的结果。 在您的情况下,您应该使用-
Element e = doc.select("p.testoprezzo").first();
String result = p.text();
使用Elements获得p标签。
class fetcher extends AsyncTask<Void,Void, Void> {
String txtValue;
@Override
protected Void doInBackground(Void... arg0) {
try {
String value = "https://mywebpage.net/";
Document document = Jsoup.connect(value).followRedirects(false).timeout(30000).get();
Element p= document.select ("p.testoprezzo").first();
txtValue = p.text();
} catch (Exception e) {
// TODO Auto-generated catch block
txtValue = null;
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
TextView valore = findViewById(R.id.textView4);
valore.setText(txtValue);
}
}
请注意, 元素和元素不同。 根据需要使用它们。 这是所有选择器的列表以及示例。
另请注意: 不要在doInBackground
方法中进行任何UI更改 ,否则您将得到一个错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.