Granite-4.0-H-350M应用案例:自动生成新闻网站数据抓取脚本

张开发
2026/4/10 8:50:08 15 分钟阅读

分享文章

Granite-4.0-H-350M应用案例:自动生成新闻网站数据抓取脚本
Granite-4.0-H-350M应用案例自动生成新闻网站数据抓取脚本1. 新闻数据抓取的需求与挑战在信息爆炸的时代新闻数据抓取已成为许多企业和研究机构的刚需。无论是舆情监控、市场分析还是内容聚合都需要从各类新闻网站高效获取结构化数据。然而传统爬虫开发面临几个典型痛点网站结构多变新闻网站的HTML结构经常调整需要频繁维护爬虫代码反爬机制复杂越来越多的网站采用动态加载、验证码等手段阻止自动化抓取开发效率低下从零开始编写爬虫需要大量时间特别是处理异常情况和数据清洗Granite-4.0-H-350M为解决这些问题提供了新思路。这个轻量级模型特别擅长理解自然语言指令并生成Python代码能快速将数据抓取需求转化为可执行脚本。相比传统方法它有三大优势快速响应变化当网站结构调整时只需重新描述需求即可获得适配的新代码智能绕过限制模型内置常见反爬应对策略生成的代码已包含基础防护措施降低技术门槛非专业开发者也能通过自然语言描述获得可用的爬虫脚本2. 环境准备与模型部署2.1 基础环境要求部署Granite-4.0-H-350M对硬件要求极低适合大多数开发环境操作系统Windows 10/macOS 10.15/Linuxx86_64内存最低4GB建议8GB以上存储空间约1GB可用空间网络能正常访问GitHub和模型仓库2.2 通过Ollama一键部署Ollama是目前最简单的本地模型运行方案支持跨平台部署# 安装Ollama以Linux为例 curl -fsSL https://ollama.com/install.sh | sh # 拉取Granite-4.0-H-350M模型 ollama pull ibm/granite4:350m-h # 启动模型服务默认端口11434 ollama serve 2.3 Python环境配置建议使用Python 3.8环境安装必要依赖pip install ollama requests beautifulsoup4 python-dotenv3. 新闻爬虫生成核心逻辑3.1 基础请求函数封装首先创建一个与模型交互的通用函数import ollama def generate_news_crawler(prompt, site_exampleNone): 生成新闻爬虫代码 :param prompt: 抓取需求描述 :param site_example: 示例网站URL或HTML片段 :return: 可执行的Python代码 full_prompt f 请生成一个Python爬虫脚本用于从新闻网站抓取以下内容 {prompt} 要求 1. 使用requests和BeautifulSoup 2. 包含完善的异常处理 3. 添加随机延时(1-3秒) 4. 设置合理的请求头 5. 输出结构化JSON数据 if site_example: full_prompt f\n示例网站结构参考\n{site_example[:500]} response ollama.chat( modelibm/granite4:350m-h, messages[{role: user, content: full_prompt}], options{temperature: 0.2} ) return extract_python_code(response[message][content]) def extract_python_code(markdown_text): 从Markdown文本提取Python代码块 start markdown_text.find(python) if start -1: return markdown_text start len(python) end markdown_text.find(, start) return markdown_text[start:end].strip()3.2 典型新闻抓取场景实践3.2.1 基础新闻列表抓取生成抓取新闻标题、链接和发布时间的代码basic_crawler generate_news_crawler( 从新闻网站首页抓取最近10条新闻的标题、链接和发布时间, 示例URL: https://example-news.com ) print(basic_crawler)模型返回的代码通常包含以下关键部分import requests from bs4 import BeautifulSoup import json import time import random def scrape_news_list(): headers { User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36..., Accept-Language: zh-CN,zh;q0.9 } try: # 请求新闻首页 response requests.get(https://example-news.com, headersheaders, timeout10) response.raise_for_status() soup BeautifulSoup(response.text, html.parser) news_items soup.select(.news-list .item)[:10] # 假设的CSS选择器 results [] for item in news_items: title item.select_one(.title).get_text(stripTrue) link item.select_one(a)[href] pub_time item.select_one(.time).get_text(stripTrue) results.append({ title: title, link: link, pub_time: pub_time }) # 添加随机延时 time.sleep(random.uniform(1, 3)) return json.dumps(results, ensure_asciiFalse) except Exception as e: print(f抓取失败: {e}) return json.dumps({error: str(e)}) if __name__ __main__: print(scrape_news_list())3.2.2 分页抓取与详情提取对于需要翻页并获取详情内容的场景paging_crawler generate_news_crawler( 抓取新闻网站前3页的新闻列表然后进入每条新闻详情页获取正文内容和作者信息, 列表页URL格式: https://example-news.com/page/2\n详情页包含.author和.content元素 )生成的代码会包含分页逻辑和嵌套请求def scrape_paged_news(): base_url https://example-news.com/page/ results [] for page in range(1, 4): # 前3页 try: response requests.get(f{base_url}{page}, timeout10) soup BeautifulSoup(response.text, html.parser) for item in soup.select(.news-item): detail_url item[href] detail_data scrape_news_detail(detail_url) results.append({ title: item.select_one(.title).text, detail: detail_data }) time.sleep(random.uniform(1, 3)) except Exception as e: print(f第{page}页抓取失败: {e}) return json.dumps(results, ensure_asciiFalse) def scrape_news_detail(url): try: response requests.get(url, timeout10) soup BeautifulSoup(response.text, html.parser) return { content: soup.select_one(.content).text.strip(), author: soup.select_one(.author).text.strip() } except Exception as e: print(f详情页抓取失败: {e}) return None4. 高级功能实现4.1 动态加载内容处理现代新闻网站常用AJAX动态加载内容模型能生成相应的处理方案ajax_crawler generate_news_crawler( 新闻列表通过API动态加载请找到API接口并抓取数据, API示例: https://example-news.com/api/news?page1 )生成的代码会直接调用API接口def scrape_api_news(): results [] api_url https://example-news.com/api/news for page in range(1, 4): try: response requests.get( api_url, params{page: page}, headers{X-Requested-With: XMLHttpRequest} ) data response.json() for item in data[items]: results.append({ title: item[title], summary: item[summary], pub_date: item[published_at] }) time.sleep(1.5) except Exception as e: print(fAPI请求失败: {e}) return json.dumps(results, ensure_asciiFalse)4.2 自动选择器生成当不确定网页结构时可以提供HTML片段让模型生成合适的选择器def generate_selectors(html_sample, targets): 根据HTML样本生成CSS选择器 :param html_sample: HTML片段 :param targets: 需要定位的元素描述 :return: 选择器字典 prompt f 根据以下HTML结构 {html_sample[:500]} 请为以下目标生成CSS选择器 {targets} response ollama.chat( modelibm/granite4:350m-h, messages[{role: user, content: prompt}] ) return parse_selector_response(response[message][content]) # 使用示例 sample_html div classnews-container article classnews-item h3 classnews-titlea href/news/123示例标题/a/h3 span classmeta2023-12-01/span /article /div selectors generate_selectors( sample_html, [新闻标题, 新闻链接, 发布时间] ) print(selectors)5. 实战优化建议5.1 性能优化技巧并发控制使用线程池提高抓取效率但注意控制并发数from concurrent.futures import ThreadPoolExecutor def batch_scrape(urls, max_workers3): with ThreadPoolExecutor(max_workersmax_workers) as executor: results list(executor.map(scrape_news_detail, urls)) return [r for r in results if r]缓存机制避免重复抓取相同内容import hashlib from pathlib import Path CACHE_DIR Path(news_cache) CACHE_DIR.mkdir(exist_okTrue) def get_cached(url): key hashlib.md5(url.encode()).hexdigest() cache_file CACHE_DIR / f{key}.json if cache_file.exists(): return json.loads(cache_file.read_text()) data scrape_news_detail(url) if data: cache_file.write_text(json.dumps(data)) return data5.2 反反爬策略请求头轮换准备多个User-Agent随机使用USER_AGENTS [ Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36..., Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15..., Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15... ] def get_random_headers(): return { User-Agent: random.choice(USER_AGENTS), Accept: text/html,application/xhtmlxml,application/xml;q0.9,image/webp,*/*;q0.8 }IP代理池使用代理IP避免被封PROXY_LIST [ http://proxy1.example.com:8080, http://proxy2.example.com:8080 ] def get_with_proxy(url): proxy random.choice(PROXY_LIST) try: response requests.get(url, proxies{http: proxy}, timeout15) return response except: return None6. 总结Granite-4.0-H-350M为新闻数据抓取提供了一种高效的新范式。通过本文介绍的方法您可以快速生成基础爬虫用自然语言描述需求即可获得可运行代码灵活适应变化当网站结构调整时只需重新生成代码智能处理复杂场景自动应对分页、动态加载等常见挑战持续优化改进基于模型建议不断优化爬虫性能和稳定性相比传统爬虫开发方式这种AI辅助的方法可以节省50%以上的开发时间特别适合需要快速响应网站变化的场景。随着模型的不断迭代其生成的代码质量和场景适应能力还将持续提升。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。

更多文章