抓取网页新闻(农业信息网的小小的规律总结:1.什么是爬虫? )
优采云 发布时间: 2021-11-16 03:12抓取网页新闻(农业信息网的小小的规律总结:1.什么是爬虫?
)
由于项目需要,我们需要用到爬虫。我自己摸索了一下,总结了一些小规则。现在我总结如下:
1.什么是爬虫?
网络爬虫是一种自动获取网页内容的程序,是搜索引擎的重要组成部分。
传统爬虫从一个或几个初始网页的网址开始,获取初始网页上的网址。在抓取网页的过程中,它不断地从当前页面中提取新的URL并将它们放入队列中,直到满足系统的某个停止条件。对于垂直搜索,聚焦爬虫,即有针对性地抓取特定主题的网页的爬虫更适合。
2. 爬虫的实现
package com.demo;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Test {
public static List findList(String url) throws IOException{ //输入某个网站查找所有新闻的地址
Connection conn = Jsoup.connect(url); //使用Jsoup获得url连接
Document doc = conn.post(); // 请求返回整个文档对象
//System.out.println(doc.html());
Elements e=doc.select("a[class=newsgray a_space2]"); //返回所有的<a>超链接标签
List list=new ArrayList();
News news=null;
for(Element element:e){
news=new News();
String title=element.toString().substring(78);
String temp=title.substring(0, title.length()-4);//新闻标题
news.setTitle(temp);
String path=element.absUrl("href"); //新闻所在路径
String content=urlToHtml(path);
news.setContent(content);
news.setUrl(path);
list.add(news);
}
return list;
}
public static String urlToHtml(String url) throws IOException{
Connection conn = Jsoup.connect(url); //使用Jsoup获得url连接
Document doc = conn.post(); // 请求返回整个文档对象
StringBuilder sb=new StringBuilder();
Elements e=doc.select("p");
for(Element element:e){
String content=element.toString();
sb.append(content);
}
return sb.toString();
}
public static void main(String[] args) throws IOException {
List list=findList("http://news.aweb.com.cn/china/hyxw/");
for(News news:list){
System.out.println(news.getContent());
}
}
}
新闻.java
package com.demo;
public class News {
private String title;
private String content;
private String url;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
比如我们想在农业信息网抓取最新的农业新闻