将http://www.sina.com/的HTML保存到c://shengchengdeHTML.html

本文介绍了一个简单的Java程序,该程序能够从指定的网址抓取HTML内容并将其保存到本地文件中。此外,还对HTML中的特定标签进行了处理,包括<style>和<script>标签。


Java code

import java.net.*;

import java.io.*;

import java.util.regex.Pattern;



public class CreateHTML {

    public static void main(String[] args) {

        CreateHTML uc = new CreateHTML();

        uc.creatHTML("http://www.sina.com/", "c://shengchengdeHTML.html");

    }



    public void creatHTML(String webURL, String local) {

        //new File(local);

        FileWriter fw = null;

        BufferedWriter bw = null;

        try {

            fw = new FileWriter(local);

            bw = new BufferedWriter(fw);

        } catch (Exception ex) {

            ex.printStackTrace();

        }

        StringBuffer document = new StringBuffer();

        try {

            URL url = new URL(webURL);

            URLConnection conn = url.openConnection();

            BufferedReader reader = new BufferedReader(new InputStreamReader(

                    conn.getInputStream()));

            String line = null;

            while ((line = reader.readLine()) != null)

                document.append(line + " ");

            reader.close();

        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

        //System.out.println(document.toString());

        String strTemp = document.toString();

        String temp = null;

        int j = 0;

        for (int i = 0; i < strTemp.length(); i++) {

            if (i<strTemp.length()&&strTemp.charAt(i) == '>') {

                j = i;

                i++;

                if (i > strTemp.length() - 2) {

                    temp = strTemp;

                    addLine(temp, bw);

                    break;

                }

                while (Pattern.compile("//s{1}").matcher("" + strTemp.charAt(i)).find()) { //跳过空格

                    i++;

                }

                if (i<strTemp.length()&&strTemp.charAt(i) == '<') {

                    temp = strTemp.substring(0, i);

                    strTemp = strTemp.substring(i, strTemp.length());

                    addLine(temp, bw);

                    i = 0;

                } else {

                    i = j;

                }

            }



            if (strTemp.substring(0, 6).equalsIgnoreCase("<style")){

                while(true){

                    if (strTemp.charAt(i) == '}') {

                        temp = strTemp.substring(0, i + 1);

                        strTemp = strTemp.substring(i + 1, strTemp.length());

                        addLine(temp, bw);

                        i = 0;

                    }

                    if(strTemp.substring(i,i+8).equalsIgnoreCase("</style>")){

                        break;

                    }

                    i++;

                }

                i=0;

            }



            if (strTemp.substring(0, 7).equalsIgnoreCase("<script")){

                while(true){

                    if (strTemp.charAt(i) == '{'||strTemp.charAt(i) == '}'||strTemp.charAt(i) == ';') {

                        temp = strTemp.substring(0, i + 1);

                        strTemp = strTemp.substring(i + 1, strTemp.length());

                        addLine(temp, bw);

                        i = -1;

                    }

                    i++;

                    if(i>=strTemp.length()-9){

                        break;

                    }

                    if(strTemp.substring(i,i+9).equalsIgnoreCase("</script>")){

                        temp = strTemp.substring(0, i);

                        strTemp = strTemp.substring(i, strTemp.length());

                        addLine(temp, bw);

                        i = 0;

                        break;

                    }

                }

            }

        }

        //将上面步骤忽略的代码加入HTML页面

        while(Pattern.compile("//s{1}").matcher("" + strTemp.charAt(0)).find()){//去掉首空格、/t等

            strTemp=strTemp.substring(1);

        }

        if(strTemp.toLowerCase().indexOf("</html>")>0){//去掉首空格等后,如果不以</html>开头,则表示上面的步骤,没有完成了所有代码的格式化。这种情况需要将剩余代码加进HTML中

            addLine(strTemp, bw);

        }

        try {

            bw.flush();

            bw.close();

            fw.close();

        } catch (Exception ex) {

            ex.printStackTrace();

        }

    }



    private void addLine(String strLine, BufferedWriter bw) {

        try {

            bw.write(strLine);

            bw.newLine();

        } catch (Exception ex) {

            ex.printStackTrace();

        }

    }

}





参考已有引用,未直接提及使用四种方法爬取https://www.sina.com.cn/的内容,但可结合常见Python爬虫方法进行推测。 ### 方法一:使用`requests`和`BeautifulSoup` `requests`库用于发送HTTP请求获取网页内容,`BeautifulSoup`用于解析HTML内容。 ```python import requests from bs4 import BeautifulSoup url = 'https://www.sina.com.cn/' response = requests.get(url) if response.status_code == 200: soup = BeautifulSoup(response.text, 'html.parser') # 这里可以根据具体需求提取内容,例如提取所有标题标签 titles = soup.find_all('title') for title in titles: print(title.text) ``` ### 方法二:使用`Scrapy`框架 `Scrapy`是一个强大的Python爬虫框架,可构建完整的爬虫项目结构。 ```python import scrapy class SinaSpider(scrapy.Spider): name = "sina" start_urls = ['https://www.sina.com.cn/'] def parse(self, response): # 这里可以根据具体需求提取内容,例如提取所有链接 for link in response.css('a::attr(href)'): yield { 'link': link.get() } ``` 要运行这个爬虫,需要在Scrapy项目中创建该爬虫文件,然后在终端执行`scrapy crawl sina`。 ### 方法三:集成`Playwright`处理JavaScript渲染的页面 如果网页内容是通过JavaScript动态加载的,可使用`Playwright`来处理。 ```python from playwright.sync_api import sync_playwright with sync_playwright() as p: browser = p.chromium.launch() page = browser.new_page() page.goto('https://www.sina.com.cn/') content = page.content() # 这里可以根据具体需求解析content print(content) browser.close() ``` ### 方法四:使用API调用 如果新浪网提供了相关API,可以直接调用API获取数据。不过需要先查找新浪网是否有公开可用的API以及对应的接口文档。假设存在一个API接口`https://api.sina.com.cn/data`: ```python import requests api_url = 'https://api.sina.com.cn/data' response = requests.get(api_url) if response.status_code == 200: data = response.json() print(data) ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值