java下载保存html页面

<span style="font-size:18px;">import java.util.*;
import java.io.*;
import java.net.*;
public class ReaderConn{
        public static void main(String[] args){
                try{
                        URLConnection conn = new URL("http://blog.youkuaiyun.com/havedream_one/article/details/44955113").openConnection();
                        conn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");
                        InputStream is = conn.getInputStream();
                        FileOutputStream out = new FileOutputStream("test");
                        int a=0;
                        while((a = is.read()) != -1){
                                out.write(a);
                        }
                        is.close();
                        out.close();
                }catch(Exception e){
                        System.out.println(e);
                }
        }
}
</span>
上文已经实现了链接,这里的小程序实现的是读取文件
Java中,你可以使用Jsoup库来解析并下载HTML文档,然后将其保存到本地文件。以下是简单的步骤: 1. **添加依赖**: 首先,你需要在你的项目中添加Jsoup的Maven或Gradle依赖。对于Maven,可以在pom.xml中添加: ```xml <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>最新版本号</version> </dependency> ``` 或者如果你使用Gradle,添加到build.gradle文件: ```gradle implementation 'org.jsoup:jsoup:最新版本号' ``` 2. **编写Java代码**: ```java import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class HTMLDownloader { public static void main(String[] args) throws Exception { // URL of the website you want to download String url = "https://example.com"; // Download and parse the HTML document Document doc = Jsoup.connect(url).get(); // Save the document as an HTML file saveDocumentAsHtml(doc, "output.html"); } private static void saveDocumentAsHtml(Document doc, String fileName) throws IOException { File outputFile = new File(fileName); outputFile.getParentFile().mkdirs(); // Create directory if needed doc.outputSettings(new OutputSettings.Builder() .prettyPrint(true) // Format the HTML for readability .encoding("UTF-8") // Specify encoding .build()); doc.write(outputFile); // Write to file } } ``` 3. **运行代码**: 运行上述代码,它会从指定URL下载HTML,然后将其保存为`output.html`文件。 **相关问题--:** 1. Jsoup库除了HTML下载,还能做些什么? 2. 如果需要定期抓取更新的内容,如何处理? 3. 如何处理网页内容中的JavaScript动态加载部分?
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值