一个简易的URL爬虫程序(java)

该程序是一个简单的Java程序,用于从指定的URL中获取网页内容并保存到本地文件。通过URL类打开指定的URL链接,并使用openStream()方法获取输入流。然后使用Scanner类读取输入流中的内容,并使用PrintWriter类将读取到的内容写入到本地文件中。

在该程序中,程序打开了腾讯新闻(https://news.qq.com/),并将网页内容保存为qq.html文件。

java 复制代码
import java.io.BufferedInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Scanner;

public class SimpleUrlCrawler {

    public static void main(String[] args) {
        try {
            // 创建URL对象,指定要抓取的网页地址
            URL url = new URL("https://news.qq.com/");

            // 打开URL连接获取输入流
            InputStream input = url.openStream();

            // 使用缓冲输入流包装输入流,提高读取效率
            Scanner cin = new Scanner(new BufferedInputStream(input));

            // 创建PrintWriter对象,用于写入文件
            PrintWriter cout = new PrintWriter(new FileWriter("qq.html"));

            // 逐行读取输入流中的内容,并写入文件
            while (cin.hasNextLine()) {
                cout.println(cin.nextLine());
            }

            // 关闭输入流、输出流
            input.close();
            cin.close();
            cout.close();
        } catch (Exception e) {
            // 处理异常
            e.printStackTrace();
        }
    }

}
相关推荐
郑州光合科技余经理1 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
大大水瓶1 天前
Tomcat
java·tomcat
dustcell.1 天前
haproxy七层代理
java·开发语言·前端
游离态指针1 天前
以为发消息=下单成功?RabbitMQ从0到秒杀实战的完整踩坑笔记
java
BD_Marathon1 天前
工厂方法模式
android·java·工厂方法模式
玹外之音1 天前
Spring AI MCP 无状态服务器实战:构建AI智能用户管理系统
java·后端
java干货1 天前
Redis 的 ZipList 是什么?它是怎么解决内存碎片问题的?
java
失重外太空啦1 天前
Tomcat
java·服务器·tomcat
屎到临头想搅便1 天前
TOMCAT
java·tomcat
Sylvia33.1 天前
火星数据:解构斯诺克每一杆进攻背后的数字语言
java·前端·python·数据挖掘·数据分析