先根據(jù)一個(gè)鏈接,抓取該頁(yè)面;解析該頁(yè)面,搜取出該頁(yè)面中有用的鏈接,根據(jù)鏈接地址循環(huán)抓取就OK了;--簡(jiǎn)單爬行器原理 抓取完文件后還需要一個(gè)功能好點(diǎn)的文檔解析器來(lái)解析出文件中的內(nèi)容;--文件解析器 再根據(jù)關(guān)鍵字(分詞器)處理這些頁(yè)面,建立自己的搜索引擎;--分詞器不好解決 我也正在搞這方面 呵呵
創(chuàng)新互聯(lián)建站公司2013年成立,先為招遠(yuǎn)等服務(wù)建站,招遠(yuǎn)等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為招遠(yuǎn)企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問(wèn)題。
//Java爬蟲demo
import?java.io.File;
import?java.net.URL;
import?java.net.URLConnection;
import?java.nio.file.Files;
import?java.nio.file.Paths;
import?java.util.Scanner;
import?java.util.UUID;
import?java.util.regex.Matcher;
import?java.util.regex.Pattern;
public?class?DownMM?{
public?static?void?main(String[]?args)?throws?Exception?{
//out為輸出的路徑,注意要以\\結(jié)尾
String?out?=?"D:\\JSP\\pic\\java\\";?
try{
File?f?=?new?File(out);
if(!?f.exists())?{??
f.mkdirs();??
}??
}catch(Exception?e){
System.out.println("no");
}
String?url?=?"-";
Pattern?reg?=?Pattern.compile("img?src=\"(.*?)\"");
for(int?j=0,?i=1;?i=10;?i++){
URL?uu?=?new?URL(url+i);
URLConnection?conn?=?uu.openConnection();
conn.setRequestProperty("User-Agent",?"Mozilla/5.0?(Windows?NT?6.3;?WOW64;?Trident/7.0;?rv:11.0)?like?Gecko");
Scanner?sc?=?new?Scanner(conn.getInputStream());
Matcher?m?=?reg.matcher(sc.useDelimiter("\\A").next());
while(m.find()){
Files.copy(new?URL(m.group(1)).openStream(),?Paths.get(out?+?UUID.randomUUID()?+?".jpg"));
System.out.println("已下載:"+j++);
}
}
}
}
網(wǎng)絡(luò)爬蟲是一個(gè)自動(dòng)提取網(wǎng)頁(yè)的程序,它為搜索引擎從萬(wàn)維網(wǎng)上下載網(wǎng)頁(yè),是搜索引擎的重要組成。
傳統(tǒng)爬蟲從一個(gè)或若干初始網(wǎng)頁(yè)的URL開始,獲得初始網(wǎng)頁(yè)上的URL,在抓取網(wǎng)頁(yè)的過(guò)程中,不斷從當(dāng)前頁(yè)面上抽取新的URL放入隊(duì)列,直到滿足系統(tǒng)的一定停止條件。對(duì)于垂直搜索來(lái)說(shuō),聚焦爬蟲,即有針對(duì)性地爬取特定主題網(wǎng)頁(yè)的爬蟲,更為適合。
以下是一個(gè)使用java實(shí)現(xiàn)的簡(jiǎn)單爬蟲核心代碼:
public void crawl() throws Throwable {
while (continueCrawling()) {
CrawlerUrl url = getNextUrl(); //獲取待爬取隊(duì)列中的下一個(gè)URL
if (url != null) {
printCrawlInfo();
String content = getContent(url); //獲取URL的文本信息
//聚焦爬蟲只爬取與主題內(nèi)容相關(guān)的網(wǎng)頁(yè),這里采用正則匹配簡(jiǎn)單處理
if (isContentRelevant(content, this.regexpSearchPattern)) {
saveContent(url, content); //保存網(wǎng)頁(yè)至本地
//獲取網(wǎng)頁(yè)內(nèi)容中的鏈接,并放入待爬取隊(duì)列中
Collection urlStrings = extractUrls(content, url);
addUrlsToUrlQueue(url, urlStrings);
} else {
System.out.println(url + " is not relevant ignoring ...");
}
//延時(shí)防止被對(duì)方屏蔽
Thread.sleep(this.delayBetweenUrls);
}
}
closeOutputStream();
}
private CrawlerUrl getNextUrl() throws Throwable {
CrawlerUrl nextUrl = null;
while ((nextUrl == null) (!urlQueue.isEmpty())) {
CrawlerUrl crawlerUrl = this.urlQueue.remove();
//doWeHavePermissionToVisit:是否有權(quán)限訪問(wèn)該URL,友好的爬蟲會(huì)根據(jù)網(wǎng)站提供的"Robot.txt"中配置的規(guī)則進(jìn)行爬取
//isUrlAlreadyVisited:URL是否訪問(wèn)過(guò),大型的搜索引擎往往采用BloomFilter進(jìn)行排重,這里簡(jiǎn)單使用HashMap
//isDepthAcceptable:是否達(dá)到指定的深度上限。爬蟲一般采取廣度優(yōu)先的方式。一些網(wǎng)站會(huì)構(gòu)建爬蟲陷阱(自動(dòng)生成一些無(wú)效鏈接使爬蟲陷入死循環(huán)),采用深度限制加以避免
if (doWeHavePermissionToVisit(crawlerUrl)
(!isUrlAlreadyVisited(crawlerUrl))
isDepthAcceptable(crawlerUrl)) {
nextUrl = crawlerUrl;
// System.out.println("Next url to be visited is " + nextUrl);
}
}
return nextUrl;
}
private String getContent(CrawlerUrl url) throws Throwable {
//HttpClient4.1的調(diào)用與之前的方式不同
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url.getUrlString());
StringBuffer strBuf = new StringBuffer();
HttpResponse response = client.execute(httpGet);
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
HttpEntity entity = response.getEntity();
if (entity != null) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(entity.getContent(), "UTF-8"));
String line = null;
if (entity.getContentLength() 0) {
strBuf = new StringBuffer((int) entity.getContentLength());
while ((line = reader.readLine()) != null) {
strBuf.append(line);
}
}
}
if (entity != null) {
nsumeContent();
}
}
//將url標(biāo)記為已訪問(wèn)
markUrlAsVisited(url);
return strBuf.toString();
}
public static boolean isContentRelevant(String content,
Pattern regexpPattern) {
boolean retValue = false;
if (content != null) {
//是否符合正則表達(dá)式的條件
Matcher m = regexpPattern.matcher(content.toLowerCase());
retValue = m.find();
}
return retValue;
}
public List extractUrls(String text, CrawlerUrl crawlerUrl) {
Map urlMap = new HashMap();
extractHttpUrls(urlMap, text);
extractRelativeUrls(urlMap, text, crawlerUrl);
return new ArrayList(urlMap.keySet());
}
private void extractHttpUrls(Map urlMap, String text) {
Matcher m = (text);
while (m.find()) {
String url = m.group();
String[] terms = url.split("a href=\"");
for (String term : terms) {
// System.out.println("Term = " + term);
if (term.startsWith("http")) {
int index = term.indexOf("\"");
if (index 0) {
term = term.substring(0, index);
}
urlMap.put(term, term);
System.out.println("Hyperlink: " + term);
}
}
}
}
private void extractRelativeUrls(Map urlMap, String text,
CrawlerUrl crawlerUrl) {
Matcher m = relativeRegexp.matcher(text);
URL textURL = crawlerUrl.getURL();
String host = textURL.getHost();
while (m.find()) {
String url = m.group();
String[] terms = url.split("a href=\"");
for (String term : terms) {
if (term.startsWith("/")) {
int index = term.indexOf("\"");
if (index 0) {
term = term.substring(0, index);
}
String s = //" + host + term;
urlMap.put(s, s);
System.out.println("Relative url: " + s);
}
}
}
}
public static void main(String[] args) {
try {
String url = "";
Queue urlQueue = new LinkedList();
String regexp = "java";
urlQueue.add(new CrawlerUrl(url, 0));
NaiveCrawler crawler = new NaiveCrawler(urlQueue, 100, 5, 1000L,
regexp);
// boolean allowCrawl = crawler.areWeAllowedToVisit(url);
// System.out.println("Allowed to crawl: " + url + " " +
// allowCrawl);
crawler.crawl();
} catch (Throwable t) {
System.out.println(t.toString());
t.printStackTrace();
}
}