Java regular expression to get all web site and link text programs

Source: Internet
Author: User

The following describes two very useful functions. You can obtain the text in the connection address and connection address of the collected string. If you need to use this function, refer to this instance.

The following is the code for java to obtain all the URL links of a webpage:

Example 1

The Code is as follows: Copy code

Import java. io .*;
Import java.net .*;
Import java. util. regex. Matcher;
Import java. util. regex. Pattern;

Import org.html parser. filters .*;
Import org.html parser .*;
Import org.html parser. nodes .*;
Import org.html parser. tags .*;
Import org.html parser. util .*;
Import org.html parser. visitors .*;

Public class GetUrl2 {
Public static void main (String args []) throws Exception {

String mystr = getwangye2 ("http://www.hzhuti.com /");

If (mystr = "")
{
System. out. println ("failed to retrieve webpage data, System exited ");
System. exit (1 );
}
System. out. println (mystr. getBytes (). length );
System. out. println (writetxt (mystr, "GetUrl2.txt "));

Mygeturl (mystr );

}

// How to handle webpage data errors? Try three times
Public static String getwangye2 (String lasturl ){
Int kk = 3;
String sss = "";
While (kk> 0 ){
Sss = getwangye (lasturl );

//! Sss. equals ("null") as sss! = "Null", but java syntax cannot be written like this

If (! Sss. equals ("null ")){
System. out. println ("Get webpage data OK ");
Return sss;
}
System. out. println ("An error occurred while retrieving webpage data. Continue ");
Try {
Thread. sleep (1500 );
} Catch (Exception e ){
System. out. println (e );
System. out. println ("sleeping ");
}

Kk --;

}

Return "";
}

// Obtain webpage data
Public static String getwangye (String surl ){
String fanstr = "null ";
Try
{
URL url = new URL (surl );
URLConnection conn = url. openConnection ();

Conn. setRequestProperty (
"User-Agent ",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv: 8.0) Gecko/20100101 Firefox/8.0 ");

// Conn. connect ();
InputStream is = conn. getInputStream ();

BufferedReader br = new BufferedReader (new InputStreamReader (is, "UTF-8 "));
String line;
String linex;
String ss = "";
While (line = br. readLine ())! = Null ){
// Linex = new String (line. getBytes ("UTF-8"), "GB2312 ");
Ss = ss + line + System. getProperty ("line. separator ");
// System. out. println (line );
}

Fanstr = ss;
Return fanstr;
} Catch (Exception e ){
// System. out. println (e );
Writer w = new StringWriter ();
E. printStackTrace (new PrintWriter (w ));
String errorstr = "system error:" + w. toString ();
System. out. println (errorstr );
Return fanstr;
}

}

// Write a text file
Public static String writetxt (String mystr, String xstr ){
Try {
FileWriter fw = new FileWriter (xstr );
Fw. write (mystr, 0, mystr. length ());
Fw. flush ();

Return "OK ";
} Catch (IOException e ){
System. out. println (e );

Return "no ";
}

}

Public static void mygeturl (String mysss) throws ParserException {
Parser myParser;
MyParser = Parser. createParser (mysss, "utf8 ");

NodeList list = myParser. parse (new NodeClassFilter (LinkTag. class ));
For (int I = 0; I <list. size (); I ++ ){
// System. out. println (list. elementAt (I). toHtml ());
String urlLink = (LinkTag) list. elementAt (I). extractLink ();
String linkName = (LinkTag) list. elementAt (I). getLinkText ();

// Output Link
System. out. println (urlLink );
// If (urlLink. indexOf ("http") = 0)
// System. out. println (linkName + ":" + urlLink );
// System. out. println (urlLink );
}

}

}

Instance 2

The Code is as follows: Copy code

Package catch_url;
Import java. io. BufferedReader;
Import java. io. InputStreamReader;
Import java.net. URL;
Import java. util. regex. Matcher;
Import java. util. regex. Pattern;

Public class Urls {
Private String startUrl; // start to collect the URL

String urlContent;

String ContentArea;

Private String strAreaBegin, strAreaEnd; // The collection area starts to collect strings and ends to collect strings.

@ SuppressWarnings ("unused ")
Private String stringInUrl, stringNotInUrl;

String strContent; // The collected content.

String [] allUrls; // All URLs collected

Private String regex; // collection rules

UrlAndTitle urlAndTitle = new UrlAndTitle (); // store the URL and title

Public static void main (String [] args)
{
Urls myurl = new Urls ("<body", "/body> ");
Myurl. getStartUrl ("http://www.bKjia. c0m /");
Myurl. getUrlContent ();
Myurl. getContentArea ();
Myurl. getStringInUrl ("http://www.bKjia. c0m /");
Myurl. getStringNotInUrl ("google ");
Myurl. Urls ();

}

// Initialize the constructors strAreaBegin and strAreaEnd.

Public Urls (String strAreaBegin, String strAreaEnd ){
This. strAreaBegin = strAreaBegin;
This. strAreaEnd = strAreaEnd;
}

//
Public void Urls ()
{
Int I = 0;
// String regex = "<
// Href = "? '? Http: // [a-zA-Z0-9] +. [a-zA-Z0-9] +. [a-zA-Z] + /? [.? [S | s] + [a>] $ ";
Final String regex = "<.*? /A> ";
// String regex = "http: //. *?> ";
Final Pattern pt = Pattern. compile (regex );
Final Matcher mt = pt. matcher (ContentArea );
While (mt. find ()){
System. out. println (mt. group ());
I ++;

// Obtain the title
Final Matcher title = Pattern. compile ("> .*? </A> "). matcher (mt. group ());
While (title. find ()){
System. out. println ("title :"
+ Title. group (). replaceAll (">|</a> ",""));
}

// Obtain the URL
Final Matcher myurl = Pattern. compile ("href =. *?> "). Matcher (mt. group ());
While (myurl. find ()){
System. out. println ("url :"
+ Myurl. group (). replaceAll ("href = |> ",""));
}

System. out. println ();

}

System. out. println ("Total" + I + "matching results ");

}

// Obtain the start collection URL
Public void getStartUrl (String startUrl)
{
This. startUrl = startUrl;
}

// Obtain the content of the website;
Public void getUrlContent ()
{

StringBuffer is = new StringBuffer ();
Try {
URL myUrl = new URL (startUrl );
BufferedReader br = new BufferedReader (new InputStreamReader (myUrl
. OpenStream ()));

String s;
While (s = br. readLine ())! = Null ){
Is. append (s );
}
UrlContent = is. toString ();
} Catch (Exception e)

{
System. out. println ("failed to output URL File ");
E. printStackTrace ();
}

}

// Obtain the matching area of the website
Public void getContentArea ()
{
Int pos1 = 0, pos2 = 0;
Pos1 = urlContent. indexOf (strAreaBegin) + strAreaBegin. length ();
Pos2 = urlContent. indexOf (strAreaEnd, pos1 );
ContentArea = urlContent. substring (pos1, pos2 );
}

// The following two functions obtain the keywords that the website should contain and those that cannot be included
// Here, we only conduct preliminary experiments. In the later stage, there should be more than one protected keyword and non-contained keyword.
Public void getStringInUrl (String stringInUrl)
{
This. stringInUrl = stringInUrl;

}

Public void getStringNotInUrl (String stringNotInUrl)
{
This. stringNotInUrl = stringNotInUrl;
}

// Obtain collection rules

// Obtain the url
Public void getUrl ()
{

}

Public String getRegex ()
{
Return regex;

}

Class UrlAndTitle {
String myURL;

String title;
}
}

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.