![](/img/trans.png)
[英]Get raw, unformatted, unmasked text from JFormattedTextField
[英]Get raw text from html
我在Android開發的基本水平上。
我想從“http://www.google.com”等頁面獲取文字。 (我將使用的頁面只有文本,所以沒有圖片或類似的東西)所以,要明確:我想在頁面上寫入文本等等我的應用程序中的字符串。
我嘗試了這段代碼,但我甚至不確定它是否符合我的要求。
URL url = new URL(/*"http://www.google.com");
URLConnection connection = url.openConnection();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
無論如何,我無法從中得到任何文字。 我該怎么做?
從您提供的示例代碼中,您甚至沒有從請求中讀取響應。 我會用以下代碼獲取html
URL u = new URL("http://www.google.com");
URLConnection conn = u.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
conn.getInputStream()));
StringBuffer buffer = new StringBuffer();
String inputLine;
while ((inputLine = in.readLine()) != null)
buffer.append(inputLine);
in.close();
System.out.println(buffer.toString());
從那里你需要將字符串傳遞給某種html解析器,如果你只想要文本。 從我所聽到的, JTidy將是一個很好的庫,但我從來沒有使用過任何Java html解析庫。
您想從HTML文件中提取文本嗎? 您可以使用專門的工具,例如Jericho HTML解析器庫。 我不確定它是否可以直接在Android應用程序中使用,它非常大,但它是開源的,因此您可以利用其代碼並僅采取您的任務所需的內容。
這是一種方式:
public String scrape(String urlString) throws Exception {
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line = null, data = "";
while ((line = reader.readLine()) != null) {
data += line + "\n";
}
return data;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.