LuisF3381/ScrapeCraft
GitHub: LuisF3381/ScrapeCraft
一个基于SeleniumBase的开源爬虫模板,提供反检测能力和多格式导出功能,帮助用户快速构建定制化的网页数据采集工具。
Stars: 0 | Forks: 0
# ScrapeCraft
开源模板,用于轻松快速地构建 Web Scraper。基于 [SeleniumBase](https://github.com/seleniumbase/SeleniumBase),这是一个内置反检测支持的自动化框架。
## 目的
ScrapeCraft 旨在成为任何想要学习 Web Scraping 或构建自己的 Scraper 用于**教育和娱乐目的**的人的起点。该模板设计为:
- **易于使用**:通过编辑 YAML 和 Python 文件配置你的 Scraper,无需触碰主代码
- **灵活**:支持多种输出格式(CSV, JSON, XML, Excel)
- **健壮**:包含日志系统、错误处理和反检测功能
## 结构
```
ScrapeCraft/
├── src/ # Codigo fuente
│ ├── main.py # Orquestacion principal
│ ├── scraper.py # Logica de extraccion de datos
│ ├── storage.py # Almacenamiento y exportacion
│ ├── driver_config.py # Configuracion del driver
│ └── logger.py # Sistema de logging
├── config/ # Configuraciones
│ ├── settings.py # Config del driver, datos y logging
│ └── web_config.yaml # URL, selectores y waits
├── tests/ # Tests de validacion
│ └── test_config.py
├── log/ # Logs de ejecucion
├── output/ # Archivos generados
├── requirements.txt
├── CHANGELOG.md
└── LICENSE
```
## 架构
项目遵循**关注点分离**原则:
```
main.py (Orquestacion)
│
├── load_web_config() # Carga config/web_config.yaml
│
├── scraper.py
│ └── scrape() # Extrae datos de la web
│
└── storage.py
├── build_filepath() # Construye rutas segun naming_mode
└── save_data() # Exporta a CSV/JSON/XML/Excel
```
### 模块
| 模块 | 职责 |
|--------|-----------------|
| `main.py` | 流程编排:加载配置,执行 scraping,保存数据 |
| `scraper.py` | 提取逻辑:导航,处理 CAPTCHA,提取元素 |
| `storage.py` | 持久化:构建路径,以多种格式导出 |
| `driver_config.py` | 使用反检测选项初始化浏览器 |
| `logger.py` | 双重日志系统(文件 + 控制台) |
## 安装
```
git clone https://github.com/tu-usuario/ScrapeCraft.git
cd ScrapeCraft
pip install -r requirements.txt
```
## 配置
### Driver (`config/settings.py`)
```
DRIVER_CONFIG = {
"headless": False, # Ejecutar sin interfaz grafica
"undetected": True, # Modo anti-deteccion
"maximize": True, # Maximizar ventana
"window_size": None, # Tamano especifico: (1920, 1080)
"user_agent": None, # User agent personalizado
"proxy": None # Proxy: "ip:puerto"
}
```
### 日志 (`config/settings.py`)
```
LOG_CONFIG = {
"log_folder": "log", # Carpeta de logs
"level": "INFO" # Nivel: DEBUG, INFO, WARNING, ERROR
}
```
日志保存在 `log/scrapecraft_YYYYMMDD.log` 中,同时也会在控制台显示。
### 数据 (`config/settings.py`)
针对每种导出格式的独立配置:
```
DATA_CONFIG = {
"csv": {
"encoding": "utf-8-sig",
"separator": ",",
"index": False
},
"json": {
"indent": 2,
"force_ascii": False,
"orient": "records"
},
"xml": {
"root": "registros",
"row": "registro"
},
"xlsx": {
"sheet_name": "Datos",
"index": False
}
}
```
代码中的用法:
```
from src.storage import save_data
# 导出为单个格式
save_data(datos, "csv", settings.DATA_CONFIG, settings.STORAGE_CONFIG)
# 导出为多种格式
for formato in ["csv", "json", "xlsx"]:
save_data(datos, formato, settings.DATA_CONFIG, settings.STORAGE_CONFIG)
```
### 存储 (`config/settings.py`)
配置文件保存的位置和方式:
```
STORAGE_CONFIG = {
"output_folder": "output",
"filename": "viviendas",
"naming_mode": "date_suffix",
"output_formats": ["csv"] # Opciones: "csv", "json", "xml", "xlsx"
}
```
同时导出为多种格式:
```
"output_formats": ["csv", "json", "xlsx"]
```
#### 命名模式 (`naming_mode`)
| 模式 | 结果 | 用途 |
|------|-----------|-----|
| `overwrite` | `output/viviendas.csv` | 始终覆盖 |
| `date_suffix` | `output/viviendas_20260130.csv` | 每天一次执行 |
| `timestamp_suffix` | `output/viviendas_20260130_143052.csv` | 每天多次执行 |
| `date_folder` | `output/20260130/viviendas.csv` | 按文件夹组织 |
### Web (`config/web_config.yaml`)
```
url: "https://ejemplo.com"
xpath_selectors:
container: '//div[@class="item"]'
Campo1: './/span[@class="dato1"]'
Campo2: './/span[@class="dato2"]'
waits:
reconnect_attempts: 3
after_load: 5
```
## 使用
```
# 执行 scraping
python -m src.main
# 执行测试
pytest tests/ -v
```
## API 参考
### scraper.py
```
def scrape(driver, web_config, logger) -> list[dict]:
"""
Extrae datos desde la URL usando los selectores del archivo de configuracion.
Args:
driver: Instancia del driver de SeleniumBase
web_config: Diccionario con url, xpath_selectors y waits
logger: Logger para registrar eventos
Returns:
Lista de diccionarios con los datos extraidos
"""
```
### storage.py
```
def save_data(datos, format, data_config, storage_config) -> None:
"""
Guarda los datos en el formato y ubicacion especificados.
Args:
datos: Lista de diccionarios con los datos a guardar
format: Formato de salida (csv, json, xml, xlsx)
data_config: Diccionario con configuraciones de cada formato
storage_config: Diccionario con configuracion de almacenamiento
"""
def build_filepath(storage_config, format) -> str:
"""
Construye la ruta del archivo segun el modo de nombrado configurado.
Args:
storage_config: Diccionario con configuracion de almacenamiento
format: Formato de salida (csv, json, xml, xlsx)
Returns:
Ruta completa del archivo a guardar
"""
```
### main.py
```
def load_web_config(logger=None, path="config/web_config.yaml") -> dict:
"""
Carga la configuracion de la web desde el archivo YAML.
Args:
logger: Logger opcional para registrar eventos
path: Ruta al archivo de configuracion
Returns:
Diccionario con url, xpath_selectors y waits
"""
def main() -> None:
"""
Funcion principal que orquesta el proceso de scraping.
Flujo:
1. Configura el logger
2. Carga la configuracion web desde YAML
3. Inicializa el driver con las opciones de settings
4. Ejecuta el scraping
5. Guarda los datos
6. Cierra el driver
"""
```
## 测试
### WebConfig
| 测试 | 描述 |
|------|-------------|
| `test_web_config_file_exists` | 验证 YAML 文件是否存在 |
| `test_web_config_has_required_keys` | 验证必需的键 |
| `test_url_format_is_valid` | 验证 URL 格式 |
| `test_xpath_selectors_format` | 验证 XPath 格式 |
| `test_waits_are_positive_numbers` | 验证等待时间为数值 |
### DataConfig
| 测试 | 描述 |
|------|-------------|
| `test_settings_has_data_config` | 验证 DATA_CONFIG 存在且至少有一种格式 |
### StorageConfig
| 测试 | 描述 |
|------|-------------|
| `test_settings_has_storage_config` | 验证 STORAGE_CONFIG 存在 |
| `test_storage_config_has_required_keys` | 验证必需的键 |
| `test_storage_config_naming_mode_is_valid` | 验证 naming_mode |
| `test_storage_config_output_folder_exists` | 验证 output 文件夹 |
### DriverConfig
| 测试 | 描述 |
|------|-------------|
| `test_settings_file_has_driver_config` | 验证 DRIVER_CONFIG |
| `test_driver_instance_created_with_settings_file` | 测试 driver 实例 |
## 需求
- Python 3.8+
- SeleniumBase
- pandas
- pyyaml
- pytest
- openpyxl
## 许可证
本项目是开源的,并在 [MIT 许可证](LICENSE) 下发布。
## 免责声明
此模板仅供教育和学习目的。在对任何网站进行 scraping 之前,请确保:
- 查看并尊重网站的服务条款
- 查阅 `robots.txt` 文件
- 不要通过过多的请求使服务器过载
- 尊重隐私和个人数据
负责任地使用 Web Scraping 是用户的责任。
标签:Python, SeleniumBase, Web Scraping, YAML配置, 代码示例, 反检测, 安全规则引擎, 开源, 数据分析, 数据提取, 数据泄露, 无后门, 无头浏览器, 模板, 浏览器自动化, 网络安全, 网络调试, 自动化, 逆向工具, 避坑, 隐私保护