( url_docs: string, recursive_depth: number = 1, current_depth: number = 1, base_url: string = "", )
| 9 | } |
| 10 | |
| 11 | export async function getNestedUrls( |
| 12 | url_docs: string, |
| 13 | recursive_depth: number = 1, |
| 14 | current_depth: number = 1, |
| 15 | base_url: string = "", |
| 16 | ): Promise<Link[]> { |
| 17 | /** |
| 18 | Get all links from a web page up to a specified recursion depth. |
| 19 | |
| 20 | url_docs: the URL of the web page |
| 21 | recursive_depth: the maximum recursion depth |
| 22 | current_depth: the current recursion depth |
| 23 | **/ |
| 24 | // TODO: Deal with # links to specific elements on a page |
| 25 | |
| 26 | // Check if we have reached the maximum recursion depth |
| 27 | if (current_depth > recursive_depth && recursive_depth !== 0) return []; |
| 28 | else if (recursive_depth == 0) return [{ name: "", href: url_docs }]; |
| 29 | const links: Link[] = []; |
| 30 | base_url = base_url || url_docs; |
| 31 | try { |
| 32 | console.log("Getting links from " + url_docs); |
| 33 | |
| 34 | const loader = new CheerioWebBaseLoader(url_docs); |
| 35 | const page = await loader.scrape(); |
| 36 | page("a").each((index, element) => { |
| 37 | const link = page(element); |
| 38 | if (link.attr("href")) { |
| 39 | links.push({ |
| 40 | name: link.text(), |
| 41 | href: makeUrlAbsolute(url_docs, link.attr("href")!), |
| 42 | }); |
| 43 | } else { |
| 44 | } |
| 45 | }); |
| 46 | } catch (e) { |
| 47 | console.log(e); |
| 48 | } |
| 49 | |
| 50 | // Try using Playwright if Cheerio doesn't come up with the goods |
| 51 | if (links.length < 5) { |
| 52 | console.log("Trying playwright"); |
| 53 | const loader = new PlaywrightWebBaseLoader(url_docs, { |
| 54 | launchOptions: { |
| 55 | headless: true, |
| 56 | }, |
| 57 | gotoOptions: { waitUntil: "domcontentloaded" }, |
| 58 | async evaluate(page: Page, browser: Browser) { |
| 59 | await page.waitForLoadState("domcontentloaded"); |
| 60 | await new Promise((resolve) => setTimeout(resolve, 5000)); |
| 61 | return await page.evaluate(() => { |
| 62 | const out = []; |
| 63 | const links = document.getElementsByTagName("a"); |
| 64 | for (const link of links) { |
| 65 | out.push({ |
| 66 | name: link.text, |
| 67 | href: link.href, |
| 68 | }); |
nothing calls this directly
no test coverage detected