聲明:
本例中的源代碼參考了:http://blog.csdn.net/qq598535550/article/details/51287630 ,并進(jìn)行修改而成的。
由于案例就是爬取的CSDN博客,分析了一下各大博客網(wǎng)站,發(fā)現(xiàn)CSDN比較適合入門,所以我也選擇CSDN作為開始,寫我的第一個(gè)爬蟲程序。
首先來介紹爬蟲的核心爬取邏輯,即PageProcessor,我們每寫一個(gè)爬蟲,都必須編寫一個(gè)針對(duì)待爬取網(wǎng)站的爬取邏輯,該類要實(shí)現(xiàn)PageProcessor接口。
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.JsonFilePipeline;
import us.codecraft.webmagic.processor.PageProcessor;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
/**
* Created by Rush on 2017/3/27.
*/
public class CsdnBlogPageProcessor implements PageProcessor {
// 部分一:抓取網(wǎng)站的相關(guān)配置,包括編碼、抓取間隔、重試次數(shù)等
private Site site = Site.me().setRetryTimes(3).setSleepTime(1000)
.setUserAgent(
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31");
// .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36");
private static String username; // 設(shè)置的Csdn用戶名
private static int size = 0; // 共抓取到的文章數(shù)量
// process是定制爬蟲邏輯的核心接口,在這里編寫抽取邏輯
public void process(Page page) {
// 部分二:定義如何抽取頁(yè)面信息,并保存下來
// 如果匹配成功,說明是文章頁(yè)
if(!page.getUrl().regex("http://blog\\.csdn\\.net/" + username + "/article/details/\\d+").match()){
// 添加所有文章頁(yè)
page.addTargetRequests(page.getHtml().xpath("http://div[@id='article_list']").links()
.regex("/" + username + "/article/details/\\d+")
.replace("/" + username + "/", "http://blog.csdn.net/" + username + "/")
.all());
// 添加其他列表頁(yè)
page.addTargetRequests(page.getHtml().xpath("http://div[@id='papelist']").links() // 限定其他列表頁(yè)獲取區(qū)域
.regex("/" + username + "/article/list/\\d+")
.replace("/" + username + "/", "http://blog.csdn.net/" + username + "/")// 巧用替換給把相對(duì)url轉(zhuǎn)換成絕對(duì)url
.all());
} else {
++size;
page.putField("numbers", page.getUrl().regex("\\d+$").get());
page.putField("authors", username);
page.putField("titles", page.getHtml()
.xpath("http://div[@class='article_title']//h1//span[@class='link_title']/a/text()").get());
page.putField("dates", page.getHtml()
.xpath("http://div[@class='article_r']//span[@class='link_postdate']/text()").get());
page.putField("tags", listToString(page.getHtml()
.xpath("http://div[@class='article_l']//span[@class='link_categories']/a/text()").all()));
page.putField("categorys", listToString(page.getHtml()
.xpath("http://div[@class='category_r']//label//span//text()").all()));
page.putField("views", page.getHtml()
.xpath("http://div[@class='article_r']//span[@class='link_view']").regex("\\d+").get());
page.putField("comments", page.getHtml()
.xpath("http://div[@class='article_r']//span[@class='link_comments']//text()").regex("\\d+").get());
page.putField("copyright", page.getHtml().regex("bog_copyright").match() ? 1 : 0);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
page.putField("dateCreated", sdf.format(new Date()));
/* 如果想要存儲(chǔ)到數(shù)據(jù)庫(kù)中,打開此代碼段,并將上面的代碼段注釋掉。
CsdnBlog csdnBlog = new CsdnBlog(
// 文章隨機(jī)編號(hào)
Integer.valueOf(page.getUrl()
.regex("\\d+$").get()),
// 文章作者
username,
// 文章標(biāo)題
page.getHtml()
.xpath("http://div[@class='article_title']//h1//span[@class='link_title']/a/text()").get(),
// 文章日期
page.getHtml()
.xpath("http://div[@class='article_r']//span[@class='link_postdate']/text()").get(),
// 文章標(biāo)簽
listToString(page.getHtml()
.xpath("http://div[@class='article_l']//span[@class='link_categories']/a/text()").all()),
// 文章類別
listToString(page.getHtml()
.xpath("http://div[@class='category_r']//label//span//text()").all()),
// 閱讀人數(shù)
Integer.valueOf(page.getHtml()
.xpath("http://div[@class='article_r']//span[@class='link_view']").regex("\\d+").get()),
// 評(píng)論人數(shù)
Integer.valueOf(page.getHtml()
.xpath("http://div[@class='article_r']//span[@class='link_comments']//text()").regex("\\d+").get()),
// 是否原創(chuàng)
page.getHtml().regex("bog_copyright").match() ? 1 : 0
);
new CsdnBlogDao().add(csdnBlog);
System.out.println(csdnBlog);
*/
}
}
public Site getSite() {
return site;
}
private static String listToString(List<String> stringList){
if(stringList == null){
return null;
}
StringBuffer result = new StringBuffer();
boolean flag = false;
for(String s : stringList){
if(flag){
result.append(',');
} else {
flag = true;
}
result.append(s);
}
return result.toString();
}
public static void main(String[] args) {
long startTime, endTime;
System.out.print("請(qǐng)輸入要爬取的CSDN博主用戶名:");
Scanner scanner = new Scanner(System.in);
username = scanner.next();
System.out.println("-----------啟動(dòng)爬蟲程序-----------");
startTime = System.currentTimeMillis();
Spider.create(new CsdnBlogPageProcessor())
.addUrl("http://blog.csdn.net/" + username)
.addPipeline(new JsonFilePipeline("D:\\webmagic\\"))
//開啟5個(gè)線程抓取
.thread(5)
//啟動(dòng)爬蟲
.run();
endTime = System.currentTimeMillis();
System.out.println("結(jié)束爬蟲程序,共抓取 " + size + " 篇文章,耗時(shí)約 " + ((endTime - startTime) / 1000) + " 秒!");
}
}
簡(jiǎn)單說明下程序:
首先輸入想要爬取的CSDN博主用戶名,然后回車即可開始爬取數(shù)據(jù),爬取完成的數(shù)據(jù)將存在D:\webmagic目錄中,當(dāng)然,你可以修改這個(gè)地址。
爬取獲得的數(shù)據(jù)將以JSON格式存儲(chǔ)在文件夾內(nèi)。
如果你想將爬取的數(shù)據(jù),保存到數(shù)據(jù)庫(kù)內(nèi)的話,可以將上面的注釋打開,并且將原注釋上方的代碼段注釋掉,然后加上下面的貼出來的代碼,即可將數(shù)據(jù)保存到數(shù)據(jù)庫(kù)中。
main()函數(shù)是java程序的入口,我們從這里開始看,開頭幾句話不用多說。
Spider.create()函數(shù)可以定義爬蟲的目標(biāo)地址以及爬取的各種參數(shù),進(jìn)程等等。
create中的addPipeline()說明了保存數(shù)據(jù)的方法,這里我使用了最基本的JsonFilePipeline方法,將數(shù)據(jù)以JSON格式保存在本地文件里面,當(dāng)然,你也可以自定義你的保存方法。
process()函數(shù),可以看出來本例中大量使用了XPath來獲取元素,想必有HTML基礎(chǔ)的人應(yīng)該可以看出來;并且還使用了正則表達(dá)式來匹配和抽取文本。其中使用page.addTargetRequests()來不斷添加要抓取的網(wǎng)頁(yè)到隊(duì)列中。
舉個(gè)例子:
我們可以看到標(biāo)題(titles)元素的抽取,使用的xpath語句是:
page.putField("titles", page.getHtml()
.xpath("http://div[@class='article_title']//h1//span[@class='link_title']/a/text()").get());

可以看到標(biāo)題的文字是在class名為article_title的div內(nèi),緊接著后面的路徑還有h1>span(class名為link_title)>a,然后a里面的文字就是文章的題目,所以可以使用形如上面的代碼來表示這一部分內(nèi)容,緊接著用get()函數(shù)取出文字。
除了get()函數(shù),WebMagic還提供了all()函數(shù),可以獲得與xpath匹配出路徑相同的所有元素的list,返回一個(gè)String列表。
另外你還可以使用regex()函數(shù)跟在xpath后面, 將抽取出來的數(shù)據(jù)進(jìn)行進(jìn)一步處理,從而產(chǎn)生出需要的數(shù)據(jù)。
如果想獲取更多更詳細(xì)的方法介紹,請(qǐng)參見http://webmagic.io/
通過以上兩種手段,就已經(jīng)可以寫出簡(jiǎn)單的爬取CSDN博客的爬蟲。
如果想將數(shù)據(jù)保存到數(shù)據(jù)庫(kù),還需要后面兩段代碼。
import java.sql.*;
/**
* Created by Rush on 2017/3/27.
*/
public class CsdnBlogDao {
private Connection conn = null;
private Statement stmt = null;
public CsdnBlogDao(){
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/spider";
String username = "root";
String password = "rush";
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
} catch (ClassNotFoundException e){
e.printStackTrace();
} catch (SQLException e){
System.out.println("數(shù)據(jù)庫(kù)連接失敗!");
e.printStackTrace();
}
}
public int add(CsdnBlog csdnBlog){
try{
String sql = "insert into spider.csdnblog(" +
"numbers, authors, titles, dates, tags, categorys, " +
"views, comments, copyright, date_created) " +
"values(" + csdnBlog.getNumbers() +
", '" + csdnBlog.getAuthors() +
"', '" + csdnBlog.getTitles() +
"', '" + csdnBlog.getDates() +
"', '" + csdnBlog.getTags() +
"', '" + csdnBlog.getCategorys() +
"', " + csdnBlog.getViews() +
", " + csdnBlog.getComments() +
", " + csdnBlog.getCopyright() +
", sysdate())";
System.out.println(sql);
PreparedStatement ps = conn.prepareStatement(sql);
int rows = stmt.executeUpdate(sql);
} catch (SQLException e){
System.out.println("插入數(shù)據(jù)失??!");
e.printStackTrace();
}
return -1;
}
}
import java.util.Date;
/**
* Created by Rush on 2017/3/27.
*/
public class CsdnBlog {
private int id;
private int numbers; // 編號(hào)
private String authors; // 作者
private String titles; // 標(biāo)題
private String dates; // 文章日期
private String tags; // 標(biāo)簽
private String categorys; // 分類
private int views; // 閱讀人數(shù)
private int comments; // 評(píng)論人數(shù)
private int copyright; // 是否原創(chuàng)
private Date dateCreated; // 爬取時(shí)間
public CsdnBlog() {}
public CsdnBlog(int numbers, String authors, String titles, String dates, String tags, String categorys, int views, int comments, int copyright) {
this.numbers = numbers;
this.authors = authors;
this.titles = titles;
this.dates = dates;
this.tags = tags;
this.categorys = categorys;
this.views = views;
this.comments = comments;
this.copyright = copyright;
}
public int getNumbers() {
return numbers;
}
public void setNumbers(int numbers) {
this.numbers = numbers;
}
public String getAuthors() {
return authors;
}
public void setAuthors(String authors) {
this.authors = authors;
}
public String getTitles() {
return titles;
}
public void setTitles(String titles) {
this.titles = titles;
}
public String getDates() {
return dates;
}
public void setDates(String date) {
this.dates = dates;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getCategorys() {
return categorys;
}
public void setCategorys(String categorys) {
this.categorys = categorys;
}
public int getViews() {
return views;
}
public void setViews(int views) {
this.views = views;
}
public int getComments() {
return comments;
}
public void setComments(int comments) {
this.comments = comments;
}
public int getCopyright() {
return copyright;
}
public void setCopyright(int copyright) {
this.copyright = copyright;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
@Override
public String toString() {
return "CsdnBlog{" +
"numbers=" + numbers +
", authors='" + authors + '\'' +
", titles='" + titles + '\'' +
", dates='" + dates + '\'' +
", tags='" + tags + '\'' +
", categorys='" + categorys + '\'' +
", views=" + views +
", comments=" + comments +
", copyright=" + copyright +
'}';
}
}
如果你想知道爬到這些數(shù)據(jù)有什么用呢?
好吧,我也不知道他們有什么用。
不過可以肯定的一點(diǎn)是:
你已經(jīng)完成了自己的第一個(gè)爬蟲程序了,不是嗎?