使用Python爬虫抓取号码的核心步骤包括确定目标、获取内容、提取数据、存储结果,以下是具体实现方法及代码示例:
方法一:正则表达式提取号码适用于从纯文本或HTML中直接匹配固定格式的号码(如电话、身份证等)。
import reimport requests# 1. 获取目标网页HTMLurl = "https://example.com"response
= requests.get(url)html_content = response.text# 2. 定义正则表达式(示例:匹配11位手机号或带区号的电话)pattern = r"(?:+86s?)?1[3-9]d{9}|(?:0d{2,3}-)?d{7,8}"phone_numbers = re.findall(pattern, html_content)# 3. 输出结果print("提取到的号码:", phone_numbers)关键点:
- 正则表达式需根据目标号码格式调整(如d{3}-d{3}-d{4}匹配123-456-7890)。
- 复杂格式可借助在线工具(如
regex101
)调试。
方法二:BeautifulSoup解析HTML适用于号码存储在HTML标签属性或特定结构中的情况。
from bs4 import BeautifulSoupimport requests# 1. 获取HTMLurl = "https://example.com"response
= requests.get(url)soup = BeautifulSoup(response.text, "html.parser")# 2. 从特定标签/属性提取(示例:从<a>标签的href或data-phone属性中提取)phone_numbers = []for tag in soup.find_all(["a", "div"]): # 根据实际标签调整 # 检查属性或文本内容 phone = tag.get("data-phone") or tag.get("href") if phone and re.match(r"^+?d[ds-]{6,}d$", str(phone)): phone_numbers.append(phone)# 3. 输出结果print("提取到的号码:", phone_numbers)关键点:
- 通过soup.find_all()定位标签,结合属性(如href、data-*)或文本内容提取。
- 需分析目标网页的HTML结构,确定号码存储位置。
完整流程示例结合异常处理和结果存储:
import reimport requestsfrom bs4 import BeautifulSoupdef scrape_phone_numbers(url): try: # 获取HTML response = requests.get(url, timeout=10) response.raise_for_status() # 检查请求是否成功 # 解析HTML soup = BeautifulSoup(response.text, "html.parser") text_content = soup.get_text() # 正则匹配号码 pattern = r"(?:+86s?)?1[3-9]d{9}" numbers = re.findall(pattern, text_content) # 去重并保存 unique_numbers = list(set(numbers)) with open("phone_numbers.txt", "w") as f: f.write("n".join(unique_numbers)) return unique_numbers except requests.exceptions.RequestException as e: print(f"请求失败: {e}") except Exception as e: print(f"发生错误: {e}")# 使用示例numbers = scrape_phone_numbers("https://example.com"
)print("保存的号码数量:", len(numbers) if numbers else 0)注意事项- 合法性:确保目标网站允许爬取(检查robots.txt或服务条款)。
- 反爬机制:添加请求头(如User-Agent)或使用selenium模拟浏览器行为。
- 性能优化:对大规模爬取,考虑使用异步库(如aiohttp)或分布式框架(如Scrapy)。
- 数据清洗:提取的号码可能需要进一步处理(如去除空格、格式化)。
通过上述方法,可灵活应对不同网页结构的号码抓取需求。实际应用中需结合目标网站特性调整策略。