使用jsoup抓取新闻信息
1,jsoup简介
jsoup 是一款Java 的HTML解析器,可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的API,可通过DOM,CSS以及类似于jQuery的操作方法来取出和操作数据。jsoup 是基于 MIT 协议发布的,可放心使用于商业项目。
jsoup 的主要功能如下:
1. 从一个 URL,文件或字符串中解析 HTML;
2. 使用 DOM 或 CSS 选择器来查找、取出数据;
3. 可操作 HTML 元素、属性、文本;
2,jsoup使用
1,下载jsoup的jar包:http://jsoup.org/download
2, jsoup英文的开发手册:http://jsoup.org/cookbook/
3,jsoup的jsoup cookbook中文版:http://www.open-open.com/jsoup/
下面是一个简单例子
1,获取新浪财经的website 以及标题,打印输出。
2,获取1中一个wensite的正文信息,打印并输出。
代码实现:
package jSoupTesting; import java.io.IOException; import org.jsoup.Jsoup;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements; public class GetSinaUrlAndTitle { public static void main(String[] args) {
// TODO Auto-generated method stub
getUrlAndTitle();
getTextMes();
} public static void getUrlAndTitle()
{
String url="http://finance.sina.com.cn/";
try {
Document doc=Jsoup.connect(url).timeout(10000).get();//get all infomation from url website
//System.out.println(doc);
Elements ListDiv = doc.getElementsByAttributeValue("class","fin_tabs0_c0");
//System.out.println(ListDiv);
for (Element div :ListDiv) {
Elements links = div.getElementsByTag("a");
// System.out.println(links);
for (Element link : links) {
String linkHref = link.attr("href").trim();
String linkText = link.text().trim();
System.out.println(linkHref+"\t"+linkText);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} public static void getTextMes()
{
String url="http://finance.sina.com.cn/hy/20140823/100220099682.shtml";
String textMes="";
try {
Document doc=Jsoup.connect(url).timeout(10000).get();
Elements ListDiv = doc.getElementsByAttributeValue("class","blkContainerSblkCon BSHARE_POP");
//System.out.println(ListDiv);
for(Element div:ListDiv)
{
Elements textInfos=div.getElementsByTag("p");
//System.out.println(textInfos);
for(Element textInfo:textInfos)
{
String text=textInfo.text().trim();
textMes=textMes+text+"\n";
}
}
System.out.println(textMes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
3,新闻抓取要求
新闻筛选过程:(以“新浪财经 “为例) http://finance.sina.com.cn/
1. 选择方向
(1)宏观新闻:宏观新闻:包括一些重大的国内外宏观调控,我国银监会等监管机构出台的一些文件,或者例如自贸区发展,金砖银行成立等国内重大金融新闻。
(2)公司新闻:包括客户公司或其他大型金融机构的管理层变动,兼并收购,战略转型,新推产品等新闻。
2. 网页选择
1.宏观新闻:进入http://finance.sina.com.cn/ -----》 首页“要闻“

2.公司新闻:进入http://finance.sina.com.cn/ 选择“银行“ -》 ”要闻“

3,抓取要求
1,要求抓取要闻部分所有网址,标题,关键字。

2,要求抓取1中网址下的正文。
3,并且前一天看过的新闻不能存在于后一天。
4,要求抓好的新闻放在txt文档中。
4,代码实现
package sinaSpider;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map; import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements; public class GetSinaInfo { public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
getSinaInforamtion();
}
public static void getSinaInforamtion()
{
Map<String,String> pathMap=createNewFiles();
try {
getSinaYaoWen(pathMap);
getSinaChangJing(pathMap);
getSinaBank(pathMap);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void getSinaYaoWen(Map<String,String> pathMap) throws IOException
{
String YaoWenTextPath=pathMap.get("yaowen")+"//yaowen"+GetDate()+"outputText.txt";
String YaoWenTitlePath=pathMap.get("yaowen")+"//yaowen"+GetDate()+"outputTitle.txt";
String YaoWenUrlPath=pathMap.get("yaowen")+"//"+GetDate()+"url.txt"; FileWriter urlWriter = new FileWriter(YaoWenUrlPath);
FileWriter textWriter = new FileWriter(YaoWenTextPath);
FileWriter titleWriter = new FileWriter(YaoWenTitlePath); String oldUrlPath=pathMap.get("yaowen")+"//"+GetYesterday()+"url.txt";
String[] oldUrls=GetYesterdayInfo(oldUrlPath); Document doc = Jsoup.connect("http://finance.sina.com.cn/").timeout(5000).get();
Elements ListDiv = doc.getElementsByAttributeValue("class","fin_tabs0_c0");
//System.out.println(ListDiv);
for (Element element :ListDiv) {
Elements links = element.getElementsByTag("a");
for (Element link : links) {
String linkHref = link.attr("href").trim();
String linkText = link.text().trim();
if(judgeDup(oldUrls,linkHref))
{
getWebText(linkHref,linkText,textWriter,titleWriter,urlWriter);
} }
}
textWriter.close();
titleWriter.close();
urlWriter.close();
} public static void getSinaChangJing(Map<String,String> pathMap) throws IOException
{
String ChanJingTextPath=pathMap.get("chanjing")+"//chanjing"+GetDate()+"outputText.txt";
String ChanJingTitlePath=pathMap.get("chanjing")+"//chanjing"+GetDate()+"outputTitle.txt";
String ChanJingUrlPath=pathMap.get("chanjing")+"//"+GetDate()+"url.txt";
FileWriter urlWriter = new FileWriter(ChanJingUrlPath);
FileWriter textWriter = new FileWriter(ChanJingTextPath);
FileWriter titleWriter = new FileWriter(ChanJingTitlePath); String oldUrlPath=pathMap.get("chanjing")+"//"+GetYesterday()+"url.txt";
String[] oldUrls=GetYesterdayInfo(oldUrlPath); Document doc = Jsoup.connect("http://finance.sina.com.cn/chanjing/").timeout(5000).get();
Elements ListDiv = doc.getElementsByAttributeValue("class","blk_03");
//System.out.println(ListDiv);
for (Element element :ListDiv) {
Elements links = element.getElementsByTag("a");
for (Element link : links) { String linkHref = link.attr("href").trim();
String linkText = link.text().trim();
if(judgeDup(oldUrls,linkHref))
{
getWebText(linkHref,linkText,textWriter,titleWriter,urlWriter);
}
}
}
textWriter.close();
titleWriter.close();
urlWriter.close();
}
public static void getSinaBank(Map<String,String> pathMap) throws IOException
{ String bankTextPath=pathMap.get("bank")+"//bank"+GetDate()+"outputText.txt";
String bankTitlePath=pathMap.get("bank")+"//bank"+GetDate()+"outputTitle.txt";
String bankUrlPath=pathMap.get("bank")+"//"+GetDate()+"url.txt";
FileWriter urlWriter = new FileWriter(bankUrlPath);
FileWriter textWriter = new FileWriter(bankTextPath);
FileWriter titleWriter = new FileWriter(bankTitlePath); String oldUrlPath=pathMap.get("bank")+"//"+GetYesterday()+"url.txt";
String[] oldUrls=GetYesterdayInfo(oldUrlPath); Document doc = Jsoup.connect("http://finance.sina.com.cn/money/bank/").timeout(5000).get();
Elements ListDiv = doc.getElementsByAttributeValue("class","blk05");
//System.out.println(ListDiv); for (Element element :ListDiv) {
Elements links = element.getElementsByTag("a");
for (Element link : links) { String linkHref = link.attr("href").trim();
String linkText = link.text().trim();
if(judgeDup(oldUrls,linkHref))
{
getWebText(linkHref,linkText,textWriter,titleWriter,urlWriter);
}
}
}
textWriter.close();
titleWriter.close();
urlWriter.close();
} public static void getWebText(String url,String subTitle,
FileWriter textWriter,FileWriter titleWriter,
FileWriter urlWriter) throws IOException
{ Document doc;
doc = Jsoup.connect(url).timeout(10000).get();
Elements ListDiv = doc.getElementsByAttributeValue("class","blkContainerSblkCon BSHARE_POP");
if(ListDiv.isEmpty()!=true)
{
String webTitleKeywords=getTitleAndWebsite(url,subTitle)+getKeyWords(doc);
System.out.println(webTitleKeywords);
writeSTK(webTitleKeywords, titleWriter);
textWriter.write(webTitleKeywords+"\n");
urlWriter.write(url+"\n");
for (Element element :ListDiv) {
Elements links = element.getElementsByTag("p");
for (Element link : links) {
String linkText = link.text().trim();
textWriter.write(linkText+"\n");
// System.out.println(linkText);
}
}
}
}
public static String getTitleAndWebsite(String url,String subTitle)
{
String titleAndWebsite;
titleAndWebsite=url+"\t"+subTitle;
return titleAndWebsite;
}
public static void writeSTK(String webTitleKeywords,FileWriter writeWebTitle)
{
try {
writeWebTitle.write(webTitleKeywords+"\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getKeyWords(Document doc)
{
Elements listKey=doc.getElementsByAttributeValue("class","art_keywords");
String keywords ="\t keywords:";
for(Element element:listKey)
{
Elements links = element.getElementsByTag("a");
for (Element link : links) {
String linkText = link.text().trim();
keywords = keywords+linkText+",";
}
}
return keywords; } public static String GetDate()
{
Date dt=new Date();
SimpleDateFormat simpleDate=new SimpleDateFormat("yyyy-MM-dd");
// System.out.println(simpleDate.format(dt));
return simpleDate.format(dt);
} public static String GetYesterday()
{
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -1);
String yestedayDate = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
// System.out.println(yestedayDate);
return yestedayDate;
}
public static String[] GetYesterdayInfo(String oldFilePath) throws IOException
{
String encoding="Utf-8";
File file=new File(oldFilePath);
if(file.exists())
{
return getOldUrls(file,encoding);
}
else
{
file.createNewFile();
return getOldUrls(file,encoding);
} }
public static String[] getOldUrls(File file,String encoding) throws IOException
{ FileInputStream fis=new FileInputStream(file);
InputStreamReader inStream=new InputStreamReader(fis,encoding);
BufferedReader input=new BufferedReader(inStream);
String url=input.readLine();
StringBuilder sb = new StringBuilder("");
while(url!=null){
sb.append(url.trim());
sb.append(",");
url=input.readLine();
}
String sbStr = sb.toString();
String oldUrls[]=sbStr.split(",");
return oldUrls; } public static boolean judgeDup(String[] oldUrls ,String newUrl)
{
for(int i=0;i<oldUrls.length;i++)
{
if(newUrl.equals(oldUrls[i])==true)
{
return false;
}
}
return true;
} public static Map<String,String> createNewFiles()
{
String path=getWorkPath()+"//output";
String [] fileNames = {"yaowen","chanjing","bank"};
Map<String,String> pathMap=new HashMap<String,String>();
String pathArray[] = new String[fileNames.length];
for(int i=0;i<fileNames.length;i++)
{
String filePath=path+"//"+fileNames[i];
File file=new File(filePath);
if(!file.exists())
{
file.mkdirs();
}
pathArray[i]=file.getPath().replace("\\", "//");
pathMap.put(fileNames[i], pathArray[i]);
}
return pathMap;
} public static String getWorkPath()
{
String workspacePath = null;
try {
File directory = new File("");//参数为空
workspacePath = directory.getCanonicalPath() ;
//System.out.println(workspacePath);
workspacePath = workspacePath.replace("\\", "//");
//System.out.println(workspacePath);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return workspacePath;
}
}
使用jsoup抓取新闻信息的更多相关文章
- HttpClient+Jsoup 抓取网页信息(网易贵金属为例)
废话不多说直接讲讲今天要做的事. 利用HttpClient和Jsoup技术抓取网页信息.HttpClient是支持HTTP协议的客户端编程工具包,并且它支持HTTP协议. jsoup 是一款基于 Ja ...
- Jsoup抓取网页数据完成一个简易的Android新闻APP
前言:作为一个篮球迷,每天必刷NBA新闻.用了那么多新闻APP,就想自己能不能也做个简易的新闻APP.于是便使用Jsoup抓取了虎扑NBA新闻的数据,完成了一个简易的新闻APP.虽然没什么技术含量,但 ...
- jsoup抓取网页+具体解说
jsoup抓取网页+具体解说 Java 程序在解析 HTML 文档时,相信大家都接触过 htmlparser 这个开源项目.我以前在 IBM DW 上发表过两篇关于 htmlparser 的文章.各自 ...
- 网络爬虫: 从allitebooks.com抓取书籍信息并从amazon.com抓取价格(3): 抓取amazon.com价格
通过上一篇随笔的处理,我们已经拿到了书的书名和ISBN码.(网络爬虫: 从allitebooks.com抓取书籍信息并从amazon.com抓取价格(2): 抓取allitebooks.com书籍信息 ...
- 网络爬虫: 从allitebooks.com抓取书籍信息并从amazon.com抓取价格(2): 抓取allitebooks.com书籍信息及ISBN码
这一篇首先从allitebooks.com里抓取书籍列表的书籍信息和每本书对应的ISBN码. 一.分析需求和网站结构 allitebooks.com这个网站的结构很简单,分页+书籍列表+书籍详情页. ...
- PHP快速抓取快递信息
<?php header("Content-type:text/html;charset=utf-8"); /** * Express.class.php 快递查询类 * @ ...
- .net抓取网页信息 - Jumony框架使用1
往往在实际开发中,经常会用到一些如抓取网站信息之类的的操作,往往大家采用的是用一些正则的方式获取,但是有时候正则是很死板的,我们常常试想能不能使用jquery的选择器,获取符合自己要求的元素,然后进行 ...
- SpringCloud系列九:SpringCloudConfig 基础配置(SpringCloudConfig 的基本概念、配置 SpringCloudConfig 服务端、抓取配置文件信息、客户端使用 SpringCloudConfig 进行配置、单仓库目录匹配、应用仓库自动选择、仓库匹配模式)
1.概念:SpringCloudConfig 基础配置 2.具体内容 通过名词就可以发现,SpringCloudConfig 核心作用一定就在于进行配置文件的管理上.也就是说为了更好的进行所有微服务的 ...
- 使用轻量级JAVA 爬虫Gecco工具抓取新闻DEMO
写在前面 最近看到Gecoo爬虫工具,感觉比较简单好用,所有写个DEMO测试一下,抓取网站 http://zj.zjol.com.cn/home.html,主要抓取新闻的标题和发布时间做为抓取测试对象 ...
随机推荐
- JAVA并发编程学习笔记------线程的三种创建方式
创建线程一般有如下几个方式: 1. 通过继承Thread类来创建一个线程: /** * 步骤1:定义一个继承Thread类的子类 * 步骤2:构造子类的一个对象 * 步骤3:启动线程: * */ pu ...
- 纯静态界面中(html)中通过js调用dll中的方法从数据库中读取数据
最近接到一个离职员工的任务,一个搭好框架的ERP系统,看了两天,说一下看到的东西,整个项目目录中我没发现一个.aspx后缀的文件,全是静态HTML文件,之后发现他用的jquery简直看的头疼,不过大概 ...
- 济南清北学堂游记 Day 0.
(摄于千佛山山顶,济南城区风光) 看似稳得一比,实则慌如老狗= = 我可能是报到最早的且实力最弱的一只. 早晨六点二十被从床上拉起来,然后在火车站附近匆忙吃了点东西就坐火车去济南了. 路途不算远,大概 ...
- .net下使用socket.io随笔记录
一.问题背景 目前公司在互联网产品上需要程序与前端部分要进行一个实时交互,在进行一定程度上的选型后,决定使用socket.io框架进行一个实践,算是公司的一个新的 尝试,也算是给自己增加增长见闻,由于 ...
- PYTHON3 RE正则表达:
The special characters are: "." Matches any character except a newline. "^" Matc ...
- PLECS—晶闸管-第九周
1. 单相桥式晶闸管整流电路仿真 (1)仿真电路图 (2)触发角为pi/4的手工波形图(参数设置,触发角=pi/4, 电感L = 0H) (2)模拟仿真波形图 1)参数设置:触发角=pi/4, 电感L ...
- Linux中的 awk查找日志中的相关记录
假设要在 api.log.201707201830 文件中,(此文件的多个字段数据以不可见字符^A(键盘上按下Ctrl+V+A)分隔),要输出第70个字段: awk -F '^A' '{print $ ...
- HTML/CSS 知识点
整个前端开发的工作流程 产品经理提出项目需求 UI出设计稿 前端人员负责开发静态页面(跟前端同步的后台人员在准备数据) 前后台的交互 测试 产品上线(后期项目维护) 互联网原理 当用户在浏览器输入网址 ...
- 获取目录-Winform
// 获取程序的基目录. System.AppDomain.CurrentDomain.BaseDirectory // 获取模块的完整路径. System.Diagnostics.Process.G ...
- Spring 中出现Element : property Bean definitions can have zero or more properties. Property elements correspond to JavaBean setter methods exposed by the bean classes. Spring supports primitives, refer
在这个ApplicationContext.xml文件中出现 如下报错 Element : property Bean definitions can have zero or more proper ...