Java爬虫的简易实现,实现爬取深度控制
使用了大佬们的方法,原文链接
链接:https://blog.csdn.net/yes7849/article/details/78121112
链接:https://www.cnblogs.com/sanmubird/p/7857474.html
效果图
功能说明
指定入口Url和爬取深度
从指定的Url里开始解析网页源码,寻找网页链接放入Links类的待访问列表
获取Links的待访问列表,对每一个待访问Url分别新建一个线程去下载内部图片,将已访问的Url加入Links的已访问列表
清空Links的待访问列表
将本次已经访问过的Url进行解析,解析到的新Url放入Links的待访问列表
重复这个过程直到完成指定深度
源码
主类,程序入口,用来获取新的Url
package com.Pic_Download;
import java.awt.AWTException;
import java.awt.Robot;
import java.io.File;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Url_ implements Runnable {
//这个是pic下载线程
private Thread t;
private String threadName;
private String Url;
Url_( String name,String Url) {
threadName = name;
this.Url = Url;
}
public void run(){
Url_Pic_Download a = new Url_Pic_Download();
Url_Pic_Download.filename = threadName;
Url_Pic_Download.downloadimg(Url);
}
public void start () {
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}
public class Get_Url {
private static Links url_link = new Links();
public static void main(String args[]) {
System.out.println();
System.out.println();
System.out.println("图片根目录(不存在会自动创建)D:/picture");
Scanner scanner = new Scanner(System.in);
Url_Download a = new Url_Download();
System.out.print("指定入口Url(默认为http://www.mmonly.cc/mmtp/nymn/):");
String inURL = scanner.next();
if(inURL.equals("")||inURL == null){
inURL = "http://www.mmonly.cc/mmtp/nymn/";
}
int Sd = 1;//默认访问深度1层
System.out.print("设置访问深度(默认为1):");
Sd = scanner.nextInt();
File Gml=new File("D:/picture");
if(!Gml.exists()){
//如果文件夹不存在
System.out.println("创建根文件夹D:/picture");
Gml.mkdir();//创建文件夹
}
//开始解析入口Url
a.setPageUrl(inURL);
String text = a.getPageSource();
String regex="[a-zA-z]+://[^\\s]*\\.+(html)";//匹配所有.html结尾的Url链接
Pattern pt=Pattern.compile(regex);
Matcher mt=pt.matcher(text);
for