从隔壁兄弟那爬点网页数据,整理成word文档
阅读原文时间:2023年07月08日阅读:1

package com.parse_report;

import com.report.utils.ParseUrl;

/**
* Create by JIUN 2018/7/14
*/
public class Main {

/\*\*  
 \* @description 主程序入口  
 \* @param args  
 \* @throws Exception  
 \*/  
public static void main(String\[\] args) throws Exception {

    new ParseUrl().cycle();

}

}

package com.report.utils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.lowagie.text.DocumentException;

public class ParseUrl {

/\*\*  
 \* @description 读取配置文件并做循环处理  
 \* @throws IOException  
 \* @throws DocumentException  
 \*/  
public void cycle() throws IOException, DocumentException {  
    int num = Integer.parseInt(Pare\_Bean.getNum());  
    String parseUtlStr = null;  
    for (int i = 1; i <= num; i++) {  
        String url = null;  
        try {  
            url = Pare\_Bean.getProp().getProperty("URL\_" + i).trim();  
            String\[\] urls = url.split(",");  
            parseUtlStr = parseUrl(urls\[0\]);  
            int ImgBiLi = 55;  
            if (urls.length >= 3) {  
                ImgBiLi = Integer.parseInt(urls\[2\]);  
            }  
            new IOTxt().IOTotxt(parseUtlStr, urls\[1\], ImgBiLi);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        if (url == null) {  
            continue;  
        }  
    }  
    System.out.println(  
            new SimpleDateFormat("yyyy-mm-dd hh:mm:ss").format(System.currentTimeMillis()) + " " + "所有文件处理完成");  
}

/\*\*  
 \* @description 解析url获取到的文本信息  
 \* @param url  
 \*            需要处理的url  
 \* @return 读取到的文本信息  
 \* @throws IOException  
 \*/  
public String parseUrl(String url) throws IOException {  
    String content = "";  
    Connection.Response response = Jsoup.connect(url).ignoreContentType(true).method(Connection.Method.GET)  
            .headers(new HashMap<String, String>() {  
                /\*\*  
                 \*  
                 \*/  
                private static final long serialVersionUID = -8566080312795794267L;

                {  
                    put("Host", "www.nmc.cn");  
                    put("Connection", "keep-alive");  
                    put("Upgrade-Insecure-Requests", "1");  
                    put("User-Agent",  
                            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36");  
                    put("Accept",  
                            "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,\*/\*;q=0.8");  
                    put("Accept-Encoding", "gzip, deflate");  
                    put("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7");  
                }  
            }).execute();

    String body = response.body();

    org.jsoup.nodes.Document parse = Jsoup.parse(body);

    Element text = parse.getElementById("text");

    // Elements select = text.select(".title");  
    // content += select.text() + "\\n";

    // select = text.select(".author");  
    // content += select.text() + "\\n";

    Elements select = text.select(".writing");  
    // content+=select.text()+"\\n";

    Element element = select.get(0);  
    Elements children = element.children();

    for (Element ele : children) {  
        if (ele.is("div")) {  
            if (ele.toString().contains("subhead")) {  
                content += ele.text() + "tttttttttttt" + "\\n";

            } else {  
                content += ele.text() + "\\n";  
                Elements img = ele.select("img");  
                if (img != null) {  
                    for (Element el : img) {  
                        content += el.attr("src") + "\\n";  
                    }  
                }  
            }  
        } else if (ele.select("p").toString().length() > 1) {  
            // 判断是否是标题  
            if (ele.select("b").toString().length() > 1) {  
                content += ele.text() + "-------------" + "\\n";  
            } else if (ele.select("p").toString().contains("text-align")) {  
                content += ele.text() + "pppppppppp" + "\\n";  
            } else {  
                content += ele.text() + "\\n";  
            }  
        }  
    }  
    return content;  
}

}

package com.report.utils;

import java.awt.Color;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.jsoup.Connection;
import org.jsoup.Jsoup;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.rtf.RtfWriter2;

/**
* @description 将文本信息写入到word文档中
* @author fan
*
*/
public class IOTxt {

/\*\*  
 \* @description 解析从url获取到的文本信息,并将文本信息写入到word文档中  
 \* @param parseUtlStr  
 \*            从url获取到的文本信息  
 \* @param filePath  
 \*            doc文档的路径  
 \* @throws DocumentException  
 \* @throws IOException  
 \*/  
public void IOTotxt(String parseUtlStr, String filePath ,int ImgBiLi) throws DocumentException, IOException {  
    BufferedReader bufferRead = null;  
    Document doc = null;  
    Paragraph par = new Paragraph();  
    Image img = null;  
    // 大标题  
    Font font = new Font(Font.BOLD, 14, Font.BOLD, new Color(0, 0, 0));  
    // BaseFont bfFont  
    // =BaseFont.createFont("SIMSUN",BaseFont.IDENTITY\_H,BaseFont.NOT\_EMBEDDED);  
    // 正文  
    Font font1 = new Font(Font.NORMAL, 12, Font.NORMAL, new Color(0, 0, 0));  
    // 小标题  
    Font font2 = new Font(Font.NORMAL, 12, Font.BOLD, new Color(0, 0, 0));  
    if (filePath.contains("yyyy")) {  
        String df = new SimpleDateFormat("yyyyMMddHH").format(new Date());  
        filePath = filePath.replace("yyyy", df);  
    }  
    File file = new File(filePath);  
    if (!file.exists()) {  
        if (!file.getParentFile().exists()) {  
            file.getParentFile().mkdirs();  
        }  
        file.createNewFile();  
    }  
    try {  
        bufferRead = new BufferedReader(new StringReader(parseUtlStr));  
        doc = new Document(PageSize.A4, 72, 72, 90, 90);  
        RtfWriter2.getInstance(doc, new FileOutputStream(new File(filePath)));  
        doc.open();  
        String aa = "";  
        par.setLeading(24);  
        int i = 1;  
        wc: while ((aa = bufferRead.readLine()) != null) {  
            if (aa.length() < 1) {  
                continue;  
            }  
            par.setFont(font1);  
            par.setAlignment(Element.ALIGN\_LEFT);  
            if (aa.contains("tttttttttttt")) {  
                par.setAlignment(Element.ALIGN\_CENTER);  
                par.setFont(font);  
                par.add(aa.replace("tttttttttttt", ""));  
                doc.add(par);  
                par.clear();  
                continue;  
            } else if (aa.contains("pppppppppp")) {  
                par.setAlignment(Element.ALIGN\_CENTER);  
                par.add(aa.replace("pppppppppp", ""));  
                doc.add(par);  
                par.clear();  
                continue;  
            } else if (aa.contains("-------------")) {  
                if (i == 1) {  
                    par.add("\\n");  
                    i++;  
                }  
                if (aa.contains("影响与关注")) {  
                    par.setFont(font2);  
                    par.add("    " + aa.replace("-------------", ""));  
                    doc.add(par);  
                    par.clear();  
                    par.setFont(font1);  
                    while ((aa = bufferRead.readLine()) != null) {  
                        if (aa.contains("http")) {  
                            break wc;  
                        }  
                        if (aa.length() < 1) {  
                            continue;  
                        }  
                        par.add("    " + aa);  
                        doc.add(par);  
                        par.clear();  
                    }  
                }  
                par.setFont(font2);  
                par.add("    " + aa.replace("-------------", ""));  
                doc.add(par);  
                par.clear();  
                continue;  
            } else if (aa.contains("http")) {  
                byte\[\] data = imageToJpg(aa);  
                img = Image.getInstance(data);  
                img.setAbsolutePosition(0, 0);  
                // img.scaleAbsolute(24, 14);  
                img.setAlignment(Image.LEFT);  
                //图片缩放比例  
                img.scalePercent(ImgBiLi);  
                par.add(img);  
                doc.add(par);  
                par.clear();  
                continue;  
            } else {  
                par.add("    " + aa);  
                doc.add(par);  
                par.clear();  
            }  
        }  
    } catch (IOException e) {  
        e.printStackTrace();  
    } finally {  
        try {  
            doc.close();  
            bufferRead.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        System.out.println(new SimpleDateFormat("yyyy-mm-dd hh:mm:ss").format(System.currentTimeMillis())  
                + " 文件写入完成:" + filePath);

    }  
}

/\*\*  
 \* @description 将从url获取到的文本中的http(图片信息)下载下来,并保存为二进制的形式  
 \* @param aa  
 \*            http的网址链接  
 \* @return 二进制的图片信息  
 \* @throws IOException  
 \* @throws DocumentException  
 \*/  
private byte\[\] imageToJpg(String aa) throws IOException, DocumentException {  
    Connection.Response execute = Jsoup.connect(aa + System.currentTimeMillis()).ignoreContentType(true).execute();  
    byte\[\] data = execute.bodyAsBytes();  
    return data;  
}

@SuppressWarnings("unused")  
private byte\[\] imageToTxt(String aa) throws IOException {  
    // new一个URL对象  
    URL url = new URL(aa);

    // 打开链接  
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // 设置请求方式为"GET"  
    conn.setRequestMethod("GET");

    // 超时响应时间为5秒  
    conn.setConnectTimeout(5 \* 1000);

    // 通过输入流获取图片数据  
    InputStream inStream = conn.getInputStream();

    // 得到图片的二进制数据,以二进制封装得到数据,具有通用性  
    byte\[\] data = readInputStream(inStream);

    // new一个文件对象用来保存图片,默认保存当前工程根目录  
    // File imageFile = new File("pic20170419.jpg");  
    // // 创建输出流  
    // FileOutputStream outStream = new FileOutputStream(imageFile);  
    // // 写入数据  
    // outStream.write(data);  
    // // 关闭输出流  
    // outStream.close();

    return data;  
}

private byte\[\] readInputStream(InputStream inStream) throws IOException {  
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();

    // 创建一个Buffer字符串  
    byte\[\] buffer = new byte\[1024\];

    // 每次读取的字符串长度,如果为-1,代表全部读取完毕  
    int len = 0;

    // 使用一个输入流从buffer里把数据读取出来  
    while ((len = inStream.read(buffer)) != -1) {  
        // 用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度  
        outStream.write(buffer, 0, len);  
    }  
    // 关闭输入流  
    inStream.close();

    // 把outStream里的数据写入内存  
    return outStream.toByteArray();  
}  

}

package com.report.utils;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Properties;

public class Pare_Bean {
private static Properties prop = null;
private static String filePath = null;
private static String num = null;
/**
* @description 加载配置文件
*/
static {
InputStream in = null;
try {
// 包内读取
in = Pare_Bean.class.getClassLoader().getResourceAsStream("parse.properties");
// jar包外读取
// in = new FileInputStream("parse.properties");

        prop = new Properties();  
        prop.load(in);  
        filePath = prop.getProperty("FILE\_PATH");  
        num = prop.getProperty("NUM");  
    } catch (IOException e) {  
        e.printStackTrace();  
    } finally {  
        try {  
            if (in != null)  
                in.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        System.out.println(new SimpleDateFormat("yyyy-mm-dd hh:mm:ss").format(System.currentTimeMillis()) + " "  
                + "属性文件加载完成,开始数据处理");  
    }  
}

public static Properties getProp() {  
    return prop;  
}

public static String getFilePath() {  
    return filePath;  
}

public static String getNum() {  
    return num;  
}

}

#配置文件中URL后面最大的一位数字
NUM=6
#格式:URL_数字=需要抓取的网址,保存路径,图片缩放比例(默认55)
URL_1=http://www.nmc.cn/publish/weather-bulletin/index.htm,d:/ybwz/gjdwgb.doc,50
URL_2=http://www.nmc.cn/publish/typhoon/warning.html,d:/ybwz/tfgb/tfyyyy.doc
URL_3=http://www.nmc.cn/publish/country/warning/typhoon.html,d:/ybwz/tfyj/tfyyyy.doc
URL_4=http://www.nmc.cn/publish/country/warning/megatemperature.html,d:/ybwz/gwyj/yyyy.doc
URL_5=http://www.nmc.cn/publish/country/warning/downpour.html,d:/ybwz/byyj/yyyy.doc
URL_6=http://www.nmc.cn/publish/country/warning/strong_convection.html,d:/ybwz/qdlyj/yyyy.doc

http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0

<groupId>com</groupId>  
<artifactId>parse\_report</artifactId>  
<version>0.0.1-SNAPSHOT</version>  
<packaging>jar</packaging>

<name>parse\_report</name>  
<url>http://maven.apache.org</url>

<properties>  
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
</properties>

<dependencies>  
    <dependency>  
        <groupId>junit</groupId>  
        <artifactId>junit</artifactId>  
        <version>4.10</version>  
        <scope>test</scope>  
    </dependency>

    <dependency>  
        <groupId>org.jsoup</groupId>  
        <artifactId>jsoup</artifactId>  
        <version>1.11.3</version>  
    </dependency>  
    <dependency>  
        <groupId>com.lowagie</groupId>  
        <artifactId>itext</artifactId>  
        <version>2.1.5</version>  
    </dependency>  
    <dependency>  
        <groupId>com.lowagie</groupId>  
        <artifactId>itext-rtf</artifactId>  
        <version>2.1.4</version>  
    </dependency>  
    <dependency>  
        <groupId>com.itextpdf</groupId>  
        <artifactId>itext-asian</artifactId>  
        <version>5.2.0</version>  
    </dependency>  
</dependencies>

maven-assembly-plugin jar-with-dependencies com.parse_report.Main make-assembly package single

爬取的网页内容模板:





天气预报 >> 天气公报













天 气 公 报
制作:陈双 徐珺  签发:马学款   2018 年  07 月  20 日  08 时 

西北地区东部至东北地区将有较强降水
台风“安比”将影响东部沿海

一、四川盆地西部和内蒙古等地出现大到暴雨

昨日,四川盆地西部、内蒙古、陕西北部、山西西北部、河北北部、北京西南部、黑龙江西南部及海南岛北部、广西南部、云南南部等地出现大到暴雨,四川盆地西部及内蒙古巴彦淖尔和鄂尔多斯、陕西榆林、北京门头沟等地出现大暴雨(100~186毫米),最大小时降雨量50~80毫米。另外,甘肃中东部出现中到大雨,甘南州合作市最大降雨量98毫米(最大小时降雨量55毫米)。

二、重点天气预报

1. 西北地区东部至东北地区将有较强降水

预计7月20日08时至21日08时,四川盆地西部、甘肃东部、宁夏南部、内蒙古中南部、黑龙江中部、广西南部、云南西部和南部等地的部分地区有大雨或暴雨,其中,黑龙江中部等地局地有大暴雨(100~130毫米),上述地区局地伴随短时强降水(最大小时降水量20~40毫米,局地50毫米以上)、雷暴大风等强对流天气。中央气象台7月20日06时继续发布暴雨蓝色预警(见图1)。

图1 全国强降雨落区预报图(7月20日08时-21日08时)

2. 台风“安比”将影响东部沿海

中央气象台7月20日06时发布台风黄色预警(见图2):预计,“安比”将以每小时15-20公里的速度向西北方向移动,21日早晨进入东海东南部,强度逐渐加强,最强可达强热带风暴级或台风级(10-12级,28-33米/秒),将于21日夜间到22日凌晨在浙江温岭到江苏启东一带沿海登陆(强热带风暴级,10-11级,25-30米/秒)。登陆后将继续向西北方向移动,强度逐渐减弱。受其影响,预计20日08时-21日08时,东海东部将有6-9级大风,东海东南部部分海域的风力有10级,阵风11-12级。

图2 台风“安比”路径概率预报图

3. 中东部地区高温天气持续

20日至21日,黄淮、江淮、江汉、江南、四川盆地、华北南部和东部、陕西南部、贵州东部、重庆、新疆南疆盆地等地的部分地区将持续出现35℃以上的高温天气,局地可达40℃。中央气象台20日06时继续发布高温黄色预警(见图3)。受台风“安比”影响,22日起高温范围明显缩小。

图3 全国高温区域预报(7月20日08时-20时)

三、未来三天具体预报

7月20日08时至21日08时,甘肃东部、宁夏、陕西北部、内蒙古中南部、河北北部、黑龙江中北部、四川盆地西部、云南西部和南部、广西南部、海南岛等地的部分地区有中到大雨,其中,甘肃东部、内蒙古河套地区、四川盆地西部、黑龙江中部、云南西部、广西南部等地局地有暴雨或大暴雨(100~130毫米);上述部分地区将伴有短时强降水(见图4)。

图4 全国降水量预报图(7月20日08时-21日08时)

7月21日08时至22日08时,陕西北部、内蒙古中南部和东北部、黑龙江北部、安徽东南部、江苏南部、上海、浙江中北部、海南岛、云南西部等地的部分地区有大到暴雨,其中,浙江西北部、海南岛西部等地局地有大暴雨(100~200毫米);上述部分地区将伴有短时强降水和雷暴大风等强对流天气(见图5)。东海大部将有8~10级、阵风11~12级大风,台风中心经过的附近海域风力可达10~11级、阵风12~13级,北部湾将有7~9级、阵风10级的大风。

图5 全国降水量预报图(7月21日08时-22日08时)

7月22日08时至23日08时,山东南部、安徽东部、江苏大部、浙江中北部、上海、华南南部沿海、海南岛、云南西部等地的部分地区有大到暴雨,其中江苏北部、浙江西北部、雷州半岛、海南岛等地有大暴雨,局地有特大暴雨(200~280毫米);上述部分地区将伴有短时强降水和雷暴大风等强对流天气(见图6)。北部湾、东海北部将有7~9级、阵风10级的大风。

图6 全国降水量预报图(7月22日08时-23日08时)

影响与关注

1、台风“安比”发展趋势及对华东地区等地的风雨影响;

2、西北地区东部、内蒙古和黑龙江等地较强降雨,关注强降雨可能引发的中小河流洪水、山洪、地质灾害以及雷暴大风等强对流天气不利影响;

3、黄淮、江淮、江汉、江南、四川盆地东部等地持续高温天气及影响;

4.广西及云南南部局地强降雨及影响。

制作: 陈双 徐珺 签发: 马学款