Extracting links from HTML

 ̄綄美尐妖づ 提交于 2019-12-13 08:36:28

问题


I am trying to extract links from HTML. I am using the following regular expression

href=\"([^\"]*)\"

Which is extracting unnecessary links. How can I write a regular expression to extract only links with class="l" like

<a href="http://users.elite.net/runner/jennifers/hello.htm" class="l">
<a href="http://www.hellodesign.com/" class="l">
<a href="http://www.ipl.org/div/hello/" class="l">

回答1:


Parsing HTML with regex is unnecessarily overcomplicated. Regex is the wrong tool for the job. Just use a normal HTML parser like Jsoup. It allows you to select HTML elements by normal CSS selectors.

Document document = Jsoup.parse(html);
Elements links = document.select("a.l"); // Select all <a class="l"> elements.

for (Element link : links) {
    System.out.println(link.absUrl("href"));
}


来源:https://stackoverflow.com/questions/9780852/extracting-links-from-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!