廣度優先爬蟲(Breadth-First Crawler)是一種遍歷或搜索樹或圖的算法。在Python中,我們可以使用隊列(Queue)來實現廣度優先爬蟲。以下是一個簡單的廣度優先爬蟲示例,用于抓取網頁內容:
requests
庫,如果沒有安裝,可以使用以下命令安裝:pip install requests
bfs_spider.py
的文件,并在其中編寫以下代碼:import requests
from bs4 import BeautifulSoup
from collections import deque
def bfs_crawl(start_url, max_depth):
visited = set()
queue = deque([(start_url, 0)])
while queue:
url, depth = queue.popleft()
if depth > max_depth:
continue
if url not in visited:
print(f"Crawling: {url} (Depth: {depth})")
visited.add(url)
try:
response = requests.get(url)
response.raise_for_status()
content = response.text
soup = BeautifulSoup(content, "html.parser")
# 提取頁面中的鏈接
links = [a["href"] for a in soup.find_all("a", href=True)]
# 將鏈接添加到隊列中
for link in links:
queue.append((link, depth + 1))
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
if __name__ == "__main__":
start_url = "https://example.com"
max_depth = 2
bfs_crawl(start_url, max_depth)
在這個示例中,我們首先導入所需的庫,然后定義一個名為bfs_crawl
的函數。這個函數接受兩個參數:起始URL和最大深度。我們使用一個隊列來存儲待爬取的URL及其深度,并使用一個集合來存儲已訪問過的URL。
在while
循環中,我們從隊列中彈出一個URL及其深度,然后檢查是否超過了最大深度。如果沒有超過,我們繼續爬取該頁面。我們使用requests
庫獲取頁面內容,并使用BeautifulSoup
庫解析HTML。然后,我們從頁面中提取所有鏈接,并將它們添加到隊列中,以便在下一輪迭代中爬取。
最后,我們在__main__
部分調用bfs_crawl
函數,傳入起始URL和最大深度。
要運行此示例,請在命令行中輸入以下命令:
python bfs_spider.py
這將啟動廣度優先爬蟲,從https://example.com
開始,爬取兩層深度內的所有網頁。