基于requests模块实现Python多深度网页爬取及邮箱采集咨询
多深度爬取实现方案
核心采用广度优先(BFS)分层遍历逻辑,完全匹配逐层爬取规则,解决原代码仅能爬取第一层的问题。
核心修改点
- 用队列按层存储待爬URL,处理完当前层所有链接后,将提取的有效链接归入下一层队列,深度计数递增,直到达到指定的最大深度即停止。
- 新增URL去重集合,避免同一页面被重复爬取、产生冗余请求甚至死循环。
- 替换原代码手动拼接相对路径的逻辑,使用Python标准库
urljoin生成标准绝对路径,避免拼接错误。 - 抽离通用爬取逻辑,避免重复代码。
- 新增基础请求头、超时处理、异常捕获,避免反爬拦截和请求异常直接导致脚本崩溃。
完整可运行代码
from bs4 import BeautifulSoup import requests import csv import re from urllib.parse import urljoin import time # 获取用户指定的最大爬取深度 while True: try: max_level_of_depth = int(input('Max level of depth for webscraping (must be a number - integer): ')) print('Do not open the input and neither the output CSV files before the script finishes!') break except: print('You must type a number (integer)! Try again...\n') # 初始化去重集合、读取csv种子URL visited = set() seed_urls = [] with open('urls.csv', mode='r', encoding='utf-8') as urls: for url in urls: cleaned_url = url.rstrip('\n').strip() if cleaned_url: seed_urls.append(cleaned_url) # 当前层待爬队列,初始为csv内的第一层URL current_layer_queue = seed_urls.copy() current_depth = 1 # 按深度循环爬取 while current_depth <= max_level_of_depth: print(f"\n===== 正在爬取第 {current_depth} 层级,本层共 {len(current_layer_queue)} 个待爬URL =====") next_layer_queue = [] # 处理当前层所有URL for target_url in current_layer_queue: # 跳过已爬过的URL if target_url in visited: continue visited.add(target_url) print(f"[第{current_depth}层] 爬取:{target_url}") # 基础请求配置 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' } # 请求异常捕获 try: page = requests.get(target_url, headers=headers, timeout=15) page.raise_for_status() except Exception as e: print(f"请求失败:{target_url},错误原因:{str(e)}") continue soup = BeautifulSoup(page.text, 'lxml') # 全页面匹配邮箱(原代码仅匹配<p>标签,此处覆盖全页面文本) page_all_text = soup.get_text() emails = re.findall(r'[a-zA-Z0-9_\-\.]+@[a-zA-Z0-9_\-\.]+\.[a-zA-Z]{2,5}', page_all_text) # 过滤无效邮箱后缀 valid_emails = [] for email in emails: if not email.lower().endswith(('.jpg', '.jpeg', '.png', '.gif')): valid_emails.append(email) # 写入结果文件 if valid_emails: with open('results.csv', mode='a', newline='', encoding='utf-8') as f: writer = csv.writer(f) # 首次写入时自动加表头(如果文件是空的) if f.tell() == 0: writer.writerow(['source_url', 'email']) for email in valid_emails: writer.writerow([target_url, email]) print(f"找到有效邮箱:{email},已存入results.csv") # 提取当前页面所有有效链接 for link_tag in soup.find_all('a', href=True): raw_href = link_tag['href'].strip() # 跳过无效链接类型 if raw_href.startswith(('#', 'javascript:', 'mailto:', 'tel:')): continue # 拼接为标准绝对路径 absolute_url = urljoin(target_url, raw_href) # 仅保留http/https开头的有效链接 if absolute_url.startswith(('http://', 'https://')): if absolute_url not in visited: next_layer_queue.append(absolute_url) # 可按需取消注释添加请求间隔,避免频率过高被封 # time.sleep(1) # 当前层处理完成,准备下一层数据 current_layer_queue = list(set(next_layer_queue)) current_depth += 1 # 下一层无待爬链接时提前终止 if not current_layer_queue: print("\n未提取到新的待爬链接,爬取提前结束") break
逻辑说明
- 深度计数从1开始,完全匹配爬取规则:第1层爬取csv内的源URL,第2层爬取第1层提取的所有链接,以此类推直到达到指定深度。
- 每层处理完后自动去重待爬URL,避免同一链接在同一层重复出现。
- 自动过滤锚点、JS、mailto类无效链接,仅爬取可访问的http/https链接。
- 写入结果时自动识别空文件并添加表头,无需手动初始化csv。
内容的提问来源于stack exchange,提问作者rogaloo
相关产品推荐
相关产品推荐

