private static String url = "路径";
private static String blogName = "路径后边所配参数";
public static void main(String[] args) {
getArticleListFromUrl(url+"/" + blogName);
System.out.println();
}
/**
* 获取文章列表
* @param listurl
*/
public static void getArticleListFromUrl(String listurl) {
Document doc = null;
try {
doc = Jsoup.connect(listurl).userAgent("Mozilla/5.0").timeout(3000).post();
} catch (IOException e) {
e.printStackTrace();
}
Elements elements = doc.getElementsByTag("a");//找到所有a标签
for (Element element : elements) {
String relHref = element.attr("href"); // == "/"这个是href的属性值,一般都是链接。这里放的是文章的连接
String title = element.attr("title");
String linkHref = element.text();
log.info("链接为2222"+element);
//用if语句过滤掉不是文章链接的内容。因为文章的链接有两个,但评论的链接只有一个,反正指向相同的页面就拿评论的链接来用吧
if (relHref.startsWith("http://") && relHref.endsWith("html") && !title.equals("")&& linkHref.equals(""))
{
log.info("链接为33333"+relHref.startsWith("http://"));
StringBuffer sb = new StringBuffer();
sb.append(relHref).append("名字为:"+title);
System.out.println();//去掉最后的#comment输出
System.out.println("链接为"+sb);//去掉最后的#comment输出
// getArticleFromUrl(sb.substring(0, sb.length() - 9));//可以通过这个url获取文章了
}
// System.out.println(linkHref);
if(linkHref.equals("2"))//如果有下一页
{
getArticleListFromUrl(url +"/" + blogName+ "/page/2");//获取下一页的列表
}
}
}
/**
* 获取文章内容
* @param detailurl
*/
public static void getArticleFromUrl(String detailurl) {
try {
Document document = Jsoup.connect(detailurl).userAgent("Mozilla/5.0").timeout(3000).post();
Element elementTitle = document.getElementsByClass("link_title").first();//标题。 这边根据class的内容来过滤
System.out.println(elementTitle.text());
String filename = elementTitle.text().replaceAll("/", "或");
Element elementContent = document.getElementsByClass("article_content").first();//内容。
saveArticle(filename , elementContent.text(), blogName);
String Content =elementContent.text().replaceAll(" ", "\t");
System.out.println(Content+elementContent.text()+"\n");
System.out.println("11111");
//也可以通过select的形式获取所需要的参数
// Elements article = document.select("div[class=article--content grap]");
// Elements time = document.select("div[class=meta--sup]");
// String context = article.html();
// System.out.println(context);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 保存文章到本地
* @param titile
* @param content
* @param blogName
*/
public static void saveArticle(String titile, String content, String blogName) {
String lujing = "d:\\MyLoadArticle\\" + blogName + "\\" + titile + ".txt";//保存到本地的路径和文件名
File file = new File(lujing);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileWriter fw = new FileWriter(file, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.flush();
bw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}