我进行了很多搜索和尝试来开发一个使用网站内容的应用程序。我刚刚看到了 StackExchange 应用程序,看起来我想开发我的应用程序。 Web 和应用程序之间的区别如下:
浏览器:
应用程序:
正如您所看到的,浏览器和应用程序之间存在一些差异。 我希望有人知道如何创建这样的应用程序,因为经过几个小时的搜索,我刚刚找到了使用简单的 WebView(就像浏览器一样 1:1)或在应用程序中使用 Javascript 来删除一些内容的解决方案(这实际上有点错误......)。
重复一遍:重点是,我想获取网站的内容(在应用程序启动时)并将其放入我的应用程序中。
干杯。
最佳答案
您想要做的是通过获取相关网站的 html 代码并使用某种形式的逻辑对其进行排序来抓取相关网站 - 我为此推荐 xPath。然后你可以将这些数据实现到一些漂亮的 native 接口(interface)中。
但是,您需要非常清楚,您获得的数据并不总是按照您想要的方式格式化,因此您的所有算法都必须非常灵活。
该过程可以分为这样的步骤
- 从网站检索数据(DefaultHttpClient 和 AsyncTask)
- 分析和检索相关数据(您的相关算法)
- 向用户显示数据(您的界面实现)
更新
贝娄是一些示例代码,用于获取实现 html-cleaner 库的网站的一些数据,您需要在项目中实现它。
class GetStationsClass extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, "iso-8859-1");
HttpPost httppost = new HttpPost("http://ntlive.dk/rt/route?id=786");
httppost.setHeader("Accept-Charset", "iso-8859-1, unicode-1-1;q=0.8");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
String data = "";
if (status != HttpStatus.SC_OK) {
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
response.getEntity().writeTo(ostream);
data = ostream.toString();
} else {
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),
"iso-8859-1"));
String line = null;
while ((line = reader.readLine()) != null) {
data += line;
}
XPath xpath = XPathFactory.newInstance().newXPath();
try {
Document document = readDocument(data);
NodeList nodes = (NodeList) xpath.evaluate("//*[@id=\"container\"]/ul/li", document,
XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
Node thisNode = nodes.item(i);
Log.v("",thisNode.getTextContent().trim);
}
} catch (XPathExpressionException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//update user interface here
}
}
private Document readDocument(String content) {
Long timeStart = new Date().getTime();
TagNode tagNode = new HtmlCleaner().clean(content);
Document doc = null;
try {
doc = new DomSerializer(new CleanerProperties()).createDOM(tagNode);
return doc;
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return doc;
}
运行上面的代码使用
new getStationsClass.execute();
关于javascript - 基于网站创建应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26614121/