网络爬虫
难度:
标签:
题目描述
代码结果
运行时间: 172 ms, 内存: 0.0 MB
/*
* LeetCode 1236: Network Crawler
* Using Java Streams to perform the crawling operation. The approach is similar to the BFS method but leverages Streams to process the URLs.
*/
import java.util.*;
import java.util.stream.*;
interface HtmlParser {
List<String> getUrls(String url);
}
public class Solution {
public List<String> crawl(String startUrl, HtmlParser htmlParser) {
String hostName = getHostName(startUrl);
Set<String> visited = Collections.synchronizedSet(new HashSet<>(Collections.singleton(startUrl)));
Queue<String> queue = new LinkedList<>(visited);
while (!queue.isEmpty()) {
String currentUrl = queue.poll();
List<String> newUrls = htmlParser.getUrls(currentUrl).stream()
.filter(url -> url.contains(hostName) && visited.add(url))
.collect(Collectors.toList());
queue.addAll(newUrls);
}
return new ArrayList<>(visited);
}
private String getHostName(String url) {
return url.split("/")[2]; // Splitting by '/' and taking the 3rd element which is the host name
}
}
解释
方法:
本题解采用广度优先搜索(BFS)策略来遍历所有与起始URL具有相同域名的网页。首先,定义一个队列来存储待访问的URL,并将起始URL加入队列和已访问集合。然后,从队列中逐个取出URL,利用HtmlParser的getUrls方法获取该URL页面上的所有链接。对于每个链接,如果它未被访问过且域名与起始URL相同,就将其加入队列和已访问集合。最终,返回已访问集合中的所有URL,即为所有可达的同域名URL。
时间复杂度:
O(N*M)
空间复杂度:
O(N)
代码细节讲解
🦆
在广度优先搜索中,如何确保不会访问到与起始URL域名不同的网页?
▷🦆
对于HtmlParser的getUrls方法,它是否能保证总是返回所有有效的链接,或者有可能返回无效或不可访问的链接?
▷🦆
在解析URL以获取域名时,如果URL格式不标准(如缺少协议头或以非标准形式出现),get_domain_name函数的行为如何?
▷🦆
在BFS的实现中,有没有可能出现队列操作(如put和get)的性能瓶颈,特别是在处理大量URL时?
▷