我希望能够获取网页的html并将其保存到String
,因此我可以对其进行一些处理。另外,我怎么能处理各种类型的压缩。
我将如何使用Java进行此操作?
答案 0 :(得分:168)
我会使用像Jsoup这样不错的HTML解析器。然后就像这样简单:
String html = Jsoup.connect("http://stackoverflow.com").get().html();
它完全透明地处理GZIP和分块响应以及字符编码。它提供了更多的优势,如CSS选择器的HTML traversing和manipulation,就像jQuery一样。您只需将其抓取为Document
,而不是String
。
Document document = Jsoup.connect("http://google.com").get();
你真的don't想要运行基本的String方法,甚至是HTML上的正则表达式来处理它。
答案 1 :(得分:103)
这是使用Java URL类的一些经过测试的代码。不过,我建议做一个比处理异常或将它们传递给调用堆栈更好的工作。
public static void main(String[] args) {
URL url;
InputStream is = null;
BufferedReader br;
String line;
try {
url = new URL("http://stackoverflow.com/");
is = url.openStream(); // throws an IOException
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (is != null) is.close();
} catch (IOException ioe) {
// nothing to see here
}
}
}
答案 2 :(得分:23)
Bill的回答非常好,但您可能希望对压缩或用户代理等请求做一些事情。以下代码显示了如何对请求进行各种类型的压缩。
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Cast shouldn't fail
HttpURLConnection.setFollowRedirects(true);
// allow both GZip and Deflate (ZLib) encodings
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
String encoding = conn.getContentEncoding();
InputStream inStr = null;
// create the appropriate stream wrapper based on
// the encoding type
if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
inStr = new GZIPInputStream(conn.getInputStream());
} else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
inStr = new InflaterInputStream(conn.getInputStream(),
new Inflater(true));
} else {
inStr = conn.getInputStream();
}
要设置user-agent,请添加以下代码:
conn.setRequestProperty ( "User-agent", "my agent name");
答案 3 :(得分:12)
嗯,您可以使用内置库,例如URL和URLConnection,但它们不会给予很多控制权。
就个人而言,我会选择Apache HTTPClient图书馆。
编辑:Apache已将HTTPClient设置为生命终止。替换为:HTTP Components
答案 4 :(得分:6)
所有上述方法都不会下载浏览器中显示的网页文本。这些天,很多数据都是通过html页面中的脚本加载到浏览器中的。上述技术都不支持脚本,它们只是下载html文本。 HTMLUNIT支持javascripts。因此,如果您要在浏览器中查找网页文本,那么您应该使用HTMLUNIT。
答案 5 :(得分:1)
这是从https网页下载html文件的示例。在以下示例中,该html文件被保存到c:\ temp \ filename.html Enjoy!
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
/**
* <b>Get the Html source from the secure url </b>
*/
public class HttpsClientUtil {
public static void main(String[] args) throws Exception {
String httpsURL = "https://stackoverflow.com";
String FILENAME = "c:\\temp\\filename.html";
BufferedWriter bw = new BufferedWriter(new FileWriter(FILENAME));
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();
con.setRequestProperty ( "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0" );
InputStream ins = con.getInputStream();
InputStreamReader isr = new InputStreamReader(ins, "Windows-1252");
BufferedReader in = new BufferedReader(isr);
String inputLine;
// Write each line into the file
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
bw.write(inputLine);
}
in.close();
bw.close();
}
}
答案 6 :(得分:1)
要使用功能强大的NIO.2 Files.copy(位于InputStream中,路径目标)进行此操作:
URL url = new URL( "http://download.me/" );
Files.copy( url.openStream(), Paths.get("downloaded.html" ) );
答案 7 :(得分:0)
在Unix / Linux机器上,您可以运行'wget',但如果您正在编写跨平台客户端,那么这不是一个真正的选择。当然,这假设您并不真正想要在下载和点击磁盘之间下载的数据中做很多事情。
答案 8 :(得分:0)
Jetty有一个HTTP客户端,可用于下载网页。
package com.zetcode;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
public class ReadWebPageEx5 {
public static void main(String[] args) throws Exception {
HttpClient client = null;
try {
client = new HttpClient();
client.start();
String url = "http://www.something.com";
ContentResponse res = client.GET(url);
System.out.println(res.getContentAsString());
} finally {
if (client != null) {
client.stop();
}
}
}
}
该示例打印简单网页的内容。
在Reading a web page in Java教程中,我编写了六个使用URL,JSoup,HtmlCleaner,Apache HttpClient,Jetty HttpClient和HtmlUnit以Java方式下载网页的示例。
答案 9 :(得分:0)
从此课程获取帮助,获取代码并过滤一些信息。
public class MainActivity extends AppCompatActivity {
EditText url;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
url = ((EditText)findViewById( R.id.editText));
DownloadCode obj = new DownloadCode();
try {
String des=" ";
String tag1= "<div class=\"description\">";
String l = obj.execute( "http://www.nu.edu.pk/Campus/Chiniot-Faisalabad/Faculty" ).get();
url.setText( l );
url.setText( " " );
String[] t1 = l.split(tag1);
String[] t2 = t1[0].split( "</div>" );
url.setText( t2[0] );
}
catch (Exception e)
{
Toast.makeText( this,e.toString(),Toast.LENGTH_SHORT ).show();
}
}
// input, extrafunctionrunparallel, output
class DownloadCode extends AsyncTask<String,Void,String>
{
@Override
protected String doInBackground(String... WebAddress) // string of webAddress separate by ','
{
String htmlcontent = " ";
try {
URL url = new URL( WebAddress[0] );
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.connect();
InputStream input = c.getInputStream();
int data;
InputStreamReader reader = new InputStreamReader( input );
data = reader.read();
while (data != -1)
{
char content = (char) data;
htmlcontent+=content;
data = reader.read();
}
}
catch (Exception e)
{
Log.i("Status : ",e.toString());
}
return htmlcontent;
}
}
}
答案 10 :(得分:-1)
我使用了这篇文章的实际答案(url)并将输出写入了一个 文件。
package test;
import java.net.*;
import java.io.*;
public class PDFTest {
public static void main(String[] args) throws Exception {
try {
URL oracle = new URL("http://www.fetagracollege.org");
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
String fileName = "D:\\a_01\\output.txt";
PrintWriter writer = new PrintWriter(fileName, "UTF-8");
OutputStream outputStream = new FileOutputStream(fileName);
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
writer.println(inputLine);
}
in.close();
} catch(Exception e) {
}
}
}