网络爬虫是一种用于在互联网上查找特定内容的程序,它可以通过遍历网页链接来收集相关信息。我们可以使用深度优先搜索(DFS)或广度优先搜索(BFS)来遍历网页链接,并提取相关内容。
我们实现一个简单的网络爬虫,使用广度优先搜索(BFS)来遍历网页链接,并提取网页内容:
import requests
from bs4 import BeautifulSoup
from collections import deque
def crawl_web(seed_url, keyword, max_pages):
"""
使用广度优先搜索(BFS)实现一个简单的网络爬虫,查找包含特定关键字的网页。
Parameters:
seed_url (str): 起始网页的URL。
keyword (str): 要查找的关键字。
max_pages (int): 最大搜索页面数。
Returns:
list: 所有包含关键字的网页链接。
"""
queue = deque([(seed_url, 1)]) # 使用队列存储待访问的网页链接和对应的深度
visited = set() # 使用集合记录已经访问过的网页链接
found_links = [] # 存储找到的包含关键字的网页链接
while queue:
url, depth = queue.popleft()
if url not in visited:
visited.add(url)
try:
response = requests.get(url)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
if keyword.lower() in soup.get_text().lower(): # 检查页面是否包含关键字
found_links.append(url)
if len(found_links) >= max_pages: # 达到最大搜索页面数时停止搜索
break
if depth < max_depth: # 设置最大搜索深度,防止无限循环
for link in soup.find_all('a', href=True):
next_url = link['href']
if next_url.startswith('http') and next_url not in visited:
queue.append((next_url, depth + 1))
except Exception as e:
print(f"Error crawling {url}: {e}")
return found_links
# 示例使用
seed_url = 'https://en.wikipedia.org/wiki/Web_scraping'
keyword = 'Python'
max_pages = 10
found_links = crawl_web(seed_url, keyword, max_pages)
print("找到的包含关键字的网页链接:")
for link in found_links:
print(link)
在上述代码中,我们首先定义了 crawl_web
函数,它接受起始网页的URL、要查找的关键字和最大搜索页面数作为参数。然后,我们使用广度优先搜索(BFS)来遍历网页链接,访问每个网页并检查是否包含关键字。如果包含关键字,则将该网页链接添加到结果列表中。为了防止爬虫陷入无限循环,我们设置了最大搜索深度。
最后,我们使用示例链接和关键字来调用 crawl_web
函数,并打印找到的包含关键字的网页链接。