利用JSOUP做爬虫,爬取我博客中的所有标题加链接,代码示例如下:
package com.test.jsoup;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class TestDemo4 {
public String baseUrl = "http://www.cnblogs.com/zhangfei/p/";
public String pager = "?page=%s";
public int getAllPageCount(){
int count = 0;
try {
Document doc = Jsoup.connect(baseUrl).get();
String countText = doc.select("#myposts>div.pager:nth-of-type(1)>.Pager").text();
countText = countText.replaceFirst("\\D+(\\d+).*", "$1");
count = Integer.valueOf(countText);
} catch (IOException e) {
e.printStackTrace();
}
return count;
}
public void crawler(){
int count = this.getAllPageCount();
for (int i = 1; i <= count; i++) {
String url = baseUrl + String.format(pager, i);
this.testJsop(url);
}
}
public void testJsop(String url) {
try {
Document doc = Jsoup.connect(url).get();
Elements element = doc.select("div.PostList a");
for (Element e : element) {
String text = e.text();
String href = e.attr("href");
System.out.println(text+" : "+href);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
TestDemo4 t = new TestDemo4();
t.crawler();
}
}
转载于:https://www.cnblogs.com/zhangfei/p/4729279.html
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/38747.html