write me a code in java to get all link in a website in jsoup
- User
write me a code in java to get all link in a website in jsoup
- Assistant
You can use JSoup to parse the HTML of a website and extract all the links (anchors) like this:
javaString url = "https://example.com/"; Document document = Jsoup.connect(url).get(); Elements links = document.select("a[href]"); for (Element link : links) { String linkHref = link.attr("href"); System.out.println(linkHref); }This will print out the href attribute of all links on the page. So in full, a basic JSoup link extractor would look like:
javaString url = "https://example.com/"; Document document = Jsoup.connect(url).get(); Elements links = document.select("a[href]"); for (Element link : links) { String linkHref = link.attr("href"); System.out.println(linkHref); } - User
Can you modify the code to get the links from all the urls recursivly?
- Assistant
Yes, we can modify the code to extract links recursively from all pages on a website using a depth-first search approach. Here's an updated Java code using Jsoup library to extract links from all pages on a website recursively:
codepublic class RecursiveLinkExtractor { private static Set<String> visitedUrls = new HashSet<>(); public static void main(String[] args) { extractLinksRecursively("https://example.com/", 0); } private static void extractLinksRecursively(String url, int depth) { if (depth > 5 || visitedUrls.contains(url)) { return; } System.out.println("Visiting " + url); visitedUrls.add(url); try { Document doc = Jsoup.connect(url).get(); Elements links = doc.select("a[href]"); for (Element link : links) { String nextUrl = link.attr("abs:href"); extractLinksRecursively(nextUrl, depth + 1); } } catch (IOException e) { e.printStackTrace(); } } }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)