1. Web Crawler
題目整理
給一個 startUrl 與 HtmlParser.getUrls(url) API,從起始頁開始爬取所有可達 URL,但只能保留與 startUrl 相同 hostname 的頁面。
解法說明
先解析出起始 hostname,然後用 BFS/DFS 掃描。每次從 queue 取 URL,呼叫 parser 拿到下一層 URL;若 hostname 相同且未看過,就加入 visited 與 queue。visited 同時避免重複爬取與 cycle。
from collections import deque
from typing import List
from urllib.parse import urlparse
class Solution:
def crawl(self, startUrl: str, htmlParser: "HtmlParser") -> List[str]:
host = urlparse(startUrl).netloc
queue = deque([startUrl])
seen = {startUrl}
while queue:
url = queue.popleft()
for next_url in htmlParser.getUrls(url):
if urlparse(next_url).netloc == host and next_url not in seen:
seen.add(next_url)
queue.append(next_url)
return list(seen)