通过正则表达式获取网站源码中的超链接
1、(?<=<a href=")http.+?(?=") 表示:搜索的字符串前面为**<a href=** 后面为**"**,字符串的开头是http,非贪婪模式
public class WebSpiderTest {
/**
* 获得URL对应的网页的源码内容
* @param urlStr
* @return
*/
public static String getURLContent(String urlStr,String charset) {
StringBuilder sb=new StringBuilder();
try {
URL url = new URL(urlStr);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(),Charset.forName(charset)));
String temp = "";
while ((temp = reader.readLine()) != null) {
sb.append(temp);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
public static List<String> getMatherSubstrs(String destStr,String regexStr){
// Pattern p=Pattern.compile("href=\"(http.+?)\""); //取到超链接地址 通过分组-java内部处理+正则表达式
// Pattern p=Pattern.compile("(?<=<a href=\")http.+?(?=\")");//通过预搜索(0宽断言)-正则表达式:(?<=<a href=")http.+?(?=")
List<String> result=new ArrayList<String>();
Pattern p=Pattern.compile(regexStr);
Matcher m=p.matcher(destStr);
while(m.find()) {
result.add(m.group(1));//通过预处理时,使用result.add(m.group());
}
return result;
}
public static void main(String[] args) {
String destStr=getURLContent("https://www.163.com", "gbk");
List<String> list=getMatherSubstrs(destStr, "href=\"(http.+?)\"");
for(String str:list) {
System.out.println(str);
}
}
}