我编写了一个程序来查找HTML页面中的所有链接:
public static void main(String[] args) throws IOException {
String base = "http://www.oracle.com/";
URL url = new URL(base);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer stringBuffer = new StringBuffer();
String inputLine = null;
while ((inputLine = in.readLine()) != null) {
stringBuffer = stringBuffer.append(inputLine).append("\n");
}
Matcher matcher = Pattern.compile("<a .*href=\"([^\"]+)\".*</a>", Pattern.DOTALL).matcher(stringBuffer.toString());
ArrayList<String> urlList = new ArrayList<>();
while (matcher.find()){
String relUrl = matcher.group(1);
String fullUrl = relUrl.startsWith("/")?base+relUrl.substring(1):relUrl;
urlList.add(fullUrl);
System.out.println(fullUrl);
}
in.close();
}
由于某种原因,当我运行此代码时,它仅匹配一个链接。但是,当我不带DOTALL
标志运行它时,它匹配108个链接。我加入该DOTALL
标记的原因是为了匹配a
标记可能会超过一行的链接,例如:
<li><a data-lbl="solutions" href="https://www.oracle.com/solutions/index.html#menu-solutions" data-trackas="hnav" class="u01nav">
<h3>Solutions</h3>
</a></li>
根据这里,正则表达式<a .*href=\"([^\"]+)\".*<\/a>
与上面的HTML匹配。(这与我在代码中使用的代码略有不同,因为Eclipse不允许我转义该/
字符)
由于您的正则表达式是贪婪的.*
,因此您的正则表达式匹配所有字符。因此,使其不贪心.*?
..
"<a .*?href=\"([^\"]+)\".*?</a>"
或者
"<a [^<>]*\\bhref=\"([^\"]+)\".*?</a>"
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句