Design and implementation of web Crawler (Java edition)

Source: Internet
Author: User

Design and implementation of web Crawler (Java edition)

Recently in order to practiced hand and the web crawler is also very interested in, decided to write a web crawler.
First look at what the crawler should be capable of.

Content from (http://www.ibm.com/developerworks/cn/java/j-lo-dyse1/index.html?ca=drs-)

The process of Web page collection is like the traversal of the graph, where the Web page is the node in the graph, and the hyperlinks in the Web page are the edges in the graph, the addresses of the other pages are obtained through the hyperlinks of the pages, so that the Web pages can be collected further, and the graph traversal is divided into the breadth first and the depth first. In conclusion, the spider collects Web pages as follows: Obtain the destination web address from the initial URL collection, receive Web page data over a network connection, add the obtained Web page data to the Web page library, and analyze other URL links in the page, and put the URL collection in the non-accessible URLs for Web collection. Represents the process:


Web page Collector gather

The Web page collector obtains the Web page data of the URL by a URL, and its implementation mainly uses the URLConnection class in Java to open the network connection of the URL corresponding page, then reads the data from the I/O stream, and BufferedReader provides a buffer to read the data. The ReadLine () row read function that is defined below the efficiency of the data read. The code is as follows (omitting the exception handling section):

                         


String line = null; while (line = Reader.readline ()) = null)
Document.append (line + "\ n");

Web page Processing

The individual pages that are collected need to be processed in two different ways, one to be placed into the Web library as the raw data for subsequent processing, and the other to be parsed to extract the URL connections and put them in the URL pool waiting for the collection of the corresponding Web pages.

The preservation of the Web page needs to be in a certain format for subsequent batch processing of the data. This paper describes a format for storing data, which is simplified from the storage format of the North Skynet:

    • A Web page library consists of a number of records, each containing a page of data information, records are stored in order to add;
    • A record consists of a data header, data, and a blank line, in order: Header + blank line + data + blank line;
    • The head consists of several attributes: version number, date, IP address, data length, arranged by attribute name and attribute value, with a colon in the middle, and one row for each attribute;
    • The data is the Web page data.

It should be explained that the reason for the date of data collection, because many of the content of the site is dynamic, such as the first page of some large portal site content, which means that if it is not crawling Web page data, it is likely to occur data expiration, so you need to add date information to identify.

URL extraction is divided into two steps, the first step is to identify the URL, the second step to the collation of the URL, two steps away mainly because some sites are linked to the use of relative paths, if not collated will produce errors. URL recognition is mainly through regular expression to match, the process first set a string as a matching string pattern, and then compiled in the pattern can use the Matcher class to match the corresponding string. The implementation code is as follows:

Public arraylist<url> Urldetector (String htmldoc)
{
Final String patternstring = "<[a| a]\\s+href= ([^>]*\\s*>) ";
Pattern pattern = pattern.compile (patternstring,pattern.case_insensitive);
arraylist<url> allurls = new arraylist<url> ();
Matcher Matcher = Pattern.matcher (Htmldoc);
String Tempurl; The first URL to match is the shape: <a href= "http://bbs.life.xxx.com.cn/" target= "_blank" >
To do this, you need to take the next step, extract the real URL,
The URL can be recorded for the first two "parts between
while (Matcher.find ()) {
try {
Tempurl = Matcher.group ();
Tempurl = tempurl.substring (Tempurl.indexof ("\" ") +1);
if (!tempurl.contains ("\")) continue;
Tempurl = tempurl.substring (0, Tempurl.indexof ("\" "));
}
catch (Malformedurlexception e)
{E.printstacktrace (); }
}
return allurls; }

According to " <[a|A]\\s+href=([^>]*\\s*>) " this regular expression can match the URL of the entire label, like " <a href="http://bbs.life.xxx.com.cn/" target="_blank"> ", so after the loop to get the entire label, you need to further extract the real URL, we can intercept the tag in the middle of the first two quotation marks to obtain the content. After that, we can get a preliminary set of URLs that belong to the page.

Next we take the second step, the URL collation, that is, the entire page of the previous acquisition of the URL collection to filter and integration. Integration is mainly for the page address is a relatively linked part, because we can easily get the URL of the current page, so the relative link only need to add a relative link field to the URL of the current page to form a complete URL, complete the integration. On the other hand, in the full URL contained in the page, there are some pages such as the ad page we do not want to crawl, or unimportant, here we mainly for the ads in the page to do a simple processing. The general website advertisement Connection all has the corresponding display expression, for example when the connection contains "ad" and so on expression, may reduce the priority of the link, so that can avoid the crawl of the advertisement link to a certain extent.

After these two steps, you can put the URL of the page collected into the URL pool, next we deal with the URL of the crawler problem.

Dispatcher Dispenser

The allocator manages the URL, which is responsible for saving the URL pool and distributing the new URL after Gather gets a webpage, and also avoids the repeated collection of pages. The allocator uses the single-instance pattern code in the design pattern, which is responsible for providing the new URL to Gather, because it is related to the multi-threaded rewriting, so the singleton mode is especially important.

Duplicate collection refers to the physical existence of a Web page, without updating the premise, is Gather repeated access, resulting in a waste of resources, mainly because there is no clear record of the URL has been visited and can not be identified. So, Dispatcher maintains two lists, "visited tables", and "table not accessed". After the page for each URL is crawled, the URL is placed in the accessed table, and the URL extracted from the page is placed in an inaccessible table, and when Gather requests a URL to Dispatcher, it first verifies that the URL is in the accessed table and then gives Gather Industry.

Spider launches multiple Gather threads

The number of pages in the Internet is now billions of dollars, and a single Gather to collect Web pages is obviously inefficient, so we need to use multi-threaded methods to improve efficiency. Gather's function is to collect Web pages, we can use the Spider class to open multiple Gather threads, so as to achieve multi-threading purposes. The code is as follows:


{

for (int i = 0; i < gathernum; i++)
{


}
}
After the thread is opened, the Web collector starts the operation of the job and, after a job is completed, requests the next job to Dispatcher, because with multithreaded Gather, in order to avoid thread insecurity, it is necessary to mutually exclusive access to Dispatcher, adding Synchronized keyword to achieve secure access to threads.

Design and implementation of web Crawler (Java edition)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.