First we encapsulate an HTTP request for the tool class, implemented with HttpURLConnection, or can be used httpclient, or directly with the Jsoup request.
Tool class implementation is relatively simple, a Get method, read the response content of the request address, which we use to crawl the content of the Web page, no use of agents, in the real crawl process, when you are a large number of requests for a site, the other party will have a series of policies to disable your request, this time the agent comes in handy, A different IP is set up by proxy to fetch data.
Public classHttputils { Public Staticstring get (string url) {Try{URL GetUrl=Newurl (URL); HttpURLConnection Connection=(HttpURLConnection) geturl.openconnection (); Connection.setrequestmethod ("GET"); Connection.setrequestproperty ("Accept", "*/*"); Connection.setrequestproperty ("User-agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; trident/4.0; CIBA) "); Connection.setrequestproperty ("Accept-language", "ZH-CN"); Connection.connect (); BufferedReader Reader=NewBufferedReader (NewInputStreamReader (Connection.getinputstream (), "Utf-8")); String Line; StringBuffer result=NewStringBuffer (); while(line = Reader.readline ())! =NULL) {result.append (line); } reader.close (); returnresult.tostring (); } Catch(Exception e) {e.printstacktrace (); } return NULL; }}
Next we look for a page with a picture, to try the crawl function
Public StaticList<string>getimagesrc (String html) {//get the IMG tag regularString Imgurl_reg = "]*?> "; //gets the regular of the SRC pathString Imgsrc_reg = "http:\"? (.*?) (\ "|>|\\s+)"; Matcher Matcher=Pattern.compile (Imgurl_reg). Matcher (HTML); List<String> Listimgurl =NewArraylist<>(); while(Matcher.find ()) {Matcher m=Pattern.compile (Imgsrc_reg). Matcher (Matcher.group ()); while(M.find ()) {Listimgurl.add (M.group (). Substring (0, M.group (). Length ()-1)); } } returnListimgurl; } Public Static voidMain (string[] args) {String URL= "http://coder520.com/"; String HTML=httputils.get (URL); List<String> Imgurls =getimagesrc (HTML); for(String imgsrc:imgurls) {System.out.println (IMGSRC); } }
First, the content of the page is crawled down, and then the regular way to parse out the page label, and then resolve the IMG address.
Execute the program we can get the following content:
http://ophdr3ukd.bkt.clouddn.com/logo.pnghttp://ophdr3ukd.bkt.clouddn.com/ Ssm.jpghttp://ophdr3ukd.bkt.clouddn.com/%e5%8d%95%e8%bd%a6.jpg
Through the above address we can download the image to the local, below we write a picture download method:
Public Static voidMain (string[] args)throwsioexception {String URL= "http://coder520.com/"; String HTML=httputils.get (URL); List<String> Imgurls =getimagesrc (HTML); File dir=NewFile ("img"); if(!dir.exists ()) {Dir.mkdir (); } for(String imgsrc:imgurls) {System.out.println (IMGSRC); String FileName= Imgsrc.substring (Imgsrc.lastindexof ("/") + 1); Files.copy (NewURL (IMGSRC). OpenStream (), Paths.get ("img/" +fileName)); } }
The running program picture is downloaded.
This is a simple implementation of a crawl and extract the image of the function, it seems to be more trouble ha, to write the regular and so on, below to introduce a more simple way, if you are familiar with jquery, the extraction element is very simple, this framework is jsoup.
Jsoup is a Java HTML parser that can parse a URL address and HTML text content directly. It provides a very labor-saving API that can be used to extract and manipulate data through dom,css and jquery-like operations.
To add Jsoup dependencies:
<dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.11.3</version>
The code extracted after using Jsoup requires only a few simple lines:
Public Static voidMain (string[] args)throwsIOException {//String url = "http://coder520.com/";//String html = httputils.get (URL);//list<string> imgurls = getimagesrc (HTML);////file dir = new file ("img");//if (!dir.exists ()) {//Dir.mkdir ();// }////For (String imgsrc:imgurls) {//System.out.println (IMGSRC);//String fileName = imgsrc.substring (Imgsrc.lastindexof ("/") + 1);//files.copy (New URL (IMGSRC). OpenStream (), Paths.get ("img/" + fileName);// }String URL= "http://coder520.com/"; String HTML=httputils.get (URL); File dir=NewFile ("img"); if(!dir.exists ()) {Dir.mkdir (); } Document Doc=jsoup.parse (HTML); //extract img TagsElements IMGs = Doc.getelementsbytag ("img"); for(Element img:imgs) {//Extract the src attribute of the img tagString imgsrc = img.attr ("src"); if(Imgsrc.startswith ("//") ) {imgsrc= "http:" +imgsrc; } System.out.println (IMGSRC); String FileName= Imgsrc.substring (Imgsrc.lastindexof ("/") + 1); Files.copy (NewURL (IMGSRC). OpenStream (), Paths.get ("img/" +fileName)); } }
Create a Document object through Jsoup.parse, and then extract all the picture tags through the Getelementsbytag method, loop through, get the src attribute of the picture by attr method, and then download the picture.
Let's upgrade it, make a small tool, provide a simple interface, enter a Web address, click the Extract button, and then download the image automatically, we can use swing to write the interface.
Public classApp { Public Static voidMain (string[] args) {JFrame frame=NewJFrame (); Frame.setresizable (false); Frame.setsize (425,400); Frame.setdefaultcloseoperation (Jframe.exit_on_close); Frame.setlayout (NULL); Frame.setlocationrelativeto (NULL); JTextField JTextField=NewJTextField (); Jtextfield.setbounds (100, 44, 200, 30); Frame.add (JTextField); JButton JButton=NewJButton ("Extract"); Jbutton.setbounds (140, 144, 100, 30); Frame.add (JButton); Frame.setvisible (true); Jbutton.addactionlistener (NewActionListener () {@Override Public voidactionperformed (ActionEvent e) {String URL=Jtextfield.gettext (); if(url = =NULL|| Url.equals ("") {Joptionpane.showmessagedialog (NULL, "Please fill in the Fetch address"); return; } File dir=NewFile ("img"); if(!dir.exists ()) {Dir.mkdir (); } String HTML=httputils.get (URL); Document Doc=jsoup.parse (HTML); Elements IMGs= Doc.getelementsbytag ("img"); for(Element img:imgs) {String imgsrc= Img.attr ("src"); if(Imgsrc.startswith ("//") ) {imgsrc= "http:" +imgsrc; } Try{System.out.println (IMGSRC); String FileName= Imgsrc.substring (Imgsrc.lastindexof ("/") + 1); Files.copy (NewURL (IMGSRC). OpenStream (), Paths.get ("img/" +fileName)); } Catch(malformedurlexception E1) {e1.printstacktrace (); } Catch(IOException E1) {e1.printstacktrace (); }} joptionpane.showmessagedialog (NULL, "Crawl Complete"); } }); }}
Enter the address and click the Extract button to download the image.
Java crawler is also very convenient