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抓取新闻信息的更多相关文章

  1. HttpClient+Jsoup 抓取网页信息(网易贵金属为例)

    废话不多说直接讲讲今天要做的事. 利用HttpClient和Jsoup技术抓取网页信息.HttpClient是支持HTTP协议的客户端编程工具包,并且它支持HTTP协议. jsoup 是一款基于 Ja ...

  2. Jsoup抓取网页数据完成一个简易的Android新闻APP

    前言:作为一个篮球迷,每天必刷NBA新闻.用了那么多新闻APP,就想自己能不能也做个简易的新闻APP.于是便使用Jsoup抓取了虎扑NBA新闻的数据,完成了一个简易的新闻APP.虽然没什么技术含量,但 ...

  3. jsoup抓取网页+具体解说

    jsoup抓取网页+具体解说 Java 程序在解析 HTML 文档时,相信大家都接触过 htmlparser 这个开源项目.我以前在 IBM DW 上发表过两篇关于 htmlparser 的文章.各自 ...

  4. 网络爬虫: 从allitebooks.com抓取书籍信息并从amazon.com抓取价格(3): 抓取amazon.com价格

    通过上一篇随笔的处理,我们已经拿到了书的书名和ISBN码.(网络爬虫: 从allitebooks.com抓取书籍信息并从amazon.com抓取价格(2): 抓取allitebooks.com书籍信息 ...

  5. 网络爬虫: 从allitebooks.com抓取书籍信息并从amazon.com抓取价格(2): 抓取allitebooks.com书籍信息及ISBN码

    这一篇首先从allitebooks.com里抓取书籍列表的书籍信息和每本书对应的ISBN码. 一.分析需求和网站结构 allitebooks.com这个网站的结构很简单,分页+书籍列表+书籍详情页. ...

  6. PHP快速抓取快递信息

    <?php header("Content-type:text/html;charset=utf-8"); /** * Express.class.php 快递查询类 * @ ...

  7. .net抓取网页信息 - Jumony框架使用1

    往往在实际开发中,经常会用到一些如抓取网站信息之类的的操作,往往大家采用的是用一些正则的方式获取,但是有时候正则是很死板的,我们常常试想能不能使用jquery的选择器,获取符合自己要求的元素,然后进行 ...

  8. SpringCloud系列九:SpringCloudConfig 基础配置(SpringCloudConfig 的基本概念、配置 SpringCloudConfig 服务端、抓取配置文件信息、客户端使用 SpringCloudConfig 进行配置、单仓库目录匹配、应用仓库自动选择、仓库匹配模式)

    1.概念:SpringCloudConfig 基础配置 2.具体内容 通过名词就可以发现,SpringCloudConfig 核心作用一定就在于进行配置文件的管理上.也就是说为了更好的进行所有微服务的 ...

  9. 使用轻量级JAVA 爬虫Gecco工具抓取新闻DEMO

    写在前面 最近看到Gecoo爬虫工具,感觉比较简单好用,所有写个DEMO测试一下,抓取网站 http://zj.zjol.com.cn/home.html,主要抓取新闻的标题和发布时间做为抓取测试对象 ...

随机推荐

  1. 弥补wxpython无背景图片缺陷

    思路: 通过设置Panel的背景样式为wx.BG_STYLE_CUSTOM: self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM) 绑定Panel的背景事情: sel ...

  2. 使用json文件给es中导入数据

    使用json文件可以给es中导入数据,10万条左右的数据可以一次导入,数量太大时导入就会报错.大数量的到导入还是需要用bulk方式. accounts.json文件格式如下: {"index ...

  3. webrtc初探之一对一的连接过程(一)

    说明,我研究的是muan-khan的一个github项目,针对的是chrome对chrome,也就是pc对pc的一对一,一对多通话,感兴趣的可以继续往下看. github地址:https://gith ...

  4. BZOJ 2006: [NOI2010]超级钢琴 [ST表+堆 | 主席树]

    题意: 一个序列,求k个不相同的长度属于\([L,R]\)的区间使得和最大 前缀和,对于每个r找最小的a[l] 然后我yy了一个可持久化线段树做法...也许会T 实际上主席树就可以了,区间k小值 然后 ...

  5. BZOJ 1492: [NOI2007]货币兑换Cash [CDQ分治 斜率优化DP]

    传送门 题意:不想写... 扔链接就跑 好吧我回来了 首先发现每次兑换一定是全部兑换,因为你兑换说明有利可图,是为了后面的某一天两种卷的汇率差别明显而兑换 那么一定拿全利啊,一定比多天的组合好 $f[ ...

  6. 《算法导论》Chapter 4 Divide-and-Conquer的学习笔记

    Introduction Divide-and-Conquer的三个步骤: Divide the problem into a number of subproblems that are small ...

  7. EFCore数据库迁移命令整理

    前言  因为现在用.net core 开发新项目,过程中需要经常涉及到数据命令的迁移,今天分别整EFCore 的两种迁移数据库的方式 1 程序包管理器控制台 , Package Manager Con ...

  8. "abc123 ,def456",反转字母,其他位置不变

    "abc123 ,def456",反转字母,其他位置不变. 无意间看到个有意思的面试题,忽然来了兴趣想着来做一下. 操作字符串用正则的效率比较高,但第一反应还是用原生来操作.下面说 ...

  9. 【Tools】ubuntu16.04升级Python2.7到3.5

    最近开始学Python,但我发现我ubuntu16.04上默认的Python是2.7,并不是3,x 于是准备Python升级,记录安装过程给初学者参考一下. 1.先取得管理员权限, 个人习惯先取得管理 ...

  10. 在Linux/Centos下用wondershaper限速

    wondershaper是国外人开发的一款在Linux内核下基于TC工具的对整块网卡的限度工具,虽然有很久没有更新了,但是测试老版本在Centos6.3上依然可以使用. 首先下载wondershape ...