Anthropic SDE Phone 面经
面试题目描述
在 Google Colab 上使用 Python 完成编程任务。主题涉及使用深度优先搜索(DFS)技术搜索具有相同域名的子网页。
主要要求
- 初始网页:以
xyz.com
为起点。 - 任务目标:搜索所有形式为
xyz.com/xxxx
的子网页。 - 过滤条件:过滤掉 URL 中包含
#
的链接。
技术细节与示例代码
使用 Python 的 requests
和 BeautifulSoup
库实现网页请求和解析。以下是基础代码示例:
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse
def is_same_domain(parent_url, new_url):
"""检查新的 URL 是否与父 URL 同域名"""
return urlparse(parent_url).netloc == urlparse(new_url).netloc
def crawl(domain, start_url):
visited = set()
stack = [start_url]
while stack:
current_url = stack.pop()
if current_url in visited:
continue
visited.add(current_url)
response = requests.get(current_url)
soup = BeautifulSoup(response.text, 'html.parser')
for link in soup.find_all('a', href=True):
href = link['href']
if '#' in href:
continue
full_url = urljoin(current_url, href)
if is_same_domain(start_url, full_url):
stack.append(full_url)
return visited
面试后续问题与讨论
效率提升
讨论如何通过 Python 的多线程和多进程来提升网页抓取的效率。
线程与进程的区别
线程(Threading):适合 I/O 密集型任务,如网页抓取,因为线程可以在等待 I/O 操作(如网络请求)期间进行切换,有效利用 CPU 时间。 进程(Multiprocessing):适合 CPU 密集型任务,因为进程可以在多个 CPU 核心上并行执行,提高计算效率。