ai agent(智能体)开发 python高级应用7: crawl4ai 0.6.3 加re正则表达式 获取百度中含有 韩立的图片要求横屏图片
遗憾本来想用ollama 本地模型 deepseek-r1:8b来获取 百度中含有 韩立的图片要求横屏图片 可惜“deepseek-r1:8b” 能力有限 只能换成 用Python re 正则表达式来解决问题了。
1. 直接处理 Markdown字符串 的优化代码,完美适配 crawl4ai
返回的字符串格式:
import asyncio
from crawl4ai import *
import redef parse_crawl4ai_md(md_content: str):"""解析 crawl4ai 返回的Markdown字符串参数:md_content (str): Markdown字符串返回:list: 前5个含"韩立"且宽>高的图片地址"""# 匹配图片地址和标题(适配crawl4ai结构)pattern = r'\* \[!\[\]\(([^)]+)\)[^\[]*?\[([^\]]+)\]'matches = re.findall(pattern, md_content)# 双重过滤(标题含"韩立" + 宽高比)results = []for url, title in matches:if '韩立' not in title:continue# 从URL参数解析尺寸(兼容多种格式)size_match = re.search(r'[?&](?:w|width)=(\d+).*?[?&](?:h|height)=(\d+)', url)if not size_match:continuetry:w, h = map(int, size_match.groups())if w > h: # 核心筛选条件results.append(url.split('?')[0]) # 移除参数保留干净URLexcept:pass# 去重并返回前5个return list(dict.fromkeys(results))[:5]async def main():print("\n--- Using CSS Selectors ---")browser_config = BrowserConfig(headless=False)crawler_config = CrawlerRunConfig(#waterfall_Pq6qhcache_mode=CacheMode.BYPASS,css_selector=".page-content_11Pd_")async with AsyncWebCrawler(config=browser_config) as crawler:result = await crawler.arun(url='https://image.baidu.com/search/index?tn=baiduimage&fm=result&ie=utf-8&word=%E9%9F%A9%E7%AB%8B%E5%9B%BE%E7%89%87',config=crawler_config,)print(result.markdown)# 调用解析函数images = parse_crawl4ai_md(result.markdown)# 打印结果print("解析结果:")for i, url in enumerate(images, 1):print(f"{i}. {url}")if __name__ == '__main__':asyncio.run(main())
2. 代码重点说明:
-
零文件依赖
直接处理内存中的Markdown字符串,无需生成临时文件 -
智能尺寸解析
正则r'[?&](?:w|width)=(\d+).*?[?&](?:h|height)=(\d+)'
支持多种参数格式:?w=800&h=600
&width=1200&height=800
?h=300&w=400
(顺序无关)
-
工业级健壮性
try-except
防御非法尺寸参数dict.fromkeys()
去重同时保留顺序url.split('?')[0]
清理跟踪参数
-
高性能处理
单次正则扫描完成数据提取,时间复杂度 O(n)
3. 结果展示:
解析结果:
1. https://img1.baidu.com/it/u=457309065,2031518686&fm=253&fmt=auto&app=120&f=JPEG
2. https://img0.baidu.com/it/u=4284382542,1530607746&fm=253&fmt=auto&app=120&f=JPEG
3. https://img1.baidu.com/it/u=937583500,4077626415&fm=253&fmt=auto&app=120&f=JPEG
4. https://img2.baidu.com/it/u=2235209624,3474576670&fm=253&fmt=auto&app=120&f=JPEG
5. https://img0.baidu.com/it/u=1099097691,2461365158&fm=253&fmt=auto&app=120&f=JPEG
4. 进阶优化方向:
-
动态尺寸验证
添加HTTP HEAD请求验证实际图片尺寸:import requests def verify_real_size(url):try:resp = requests.head(url, timeout=2, allow_redirects=True)if resp.status_code == 200:content_type = resp.headers.get('Content-Type', '')if 'image/' in content_type:# 从Header或解析二进制获取真实尺寸return (width, height) except:return (0, 0)
-
异步处理(非必需)
使用asyncio
+aiohttp
加速批量验证:import aiohttp async def async_verify(url):async with aiohttp.ClientSession() as session:async with session.head(url) as resp:# 获取尺寸逻辑return await process_response(resp)
-
缓存机制(非必需)
用lru_cache
缓存已解析的URL尺寸信息:from functools import lru_cache @lru_cache(maxsize=1000) def get_cached_size(url):return verify_real_size(url)
4. 要是能升级显卡硬件的话,本地:deepseek-r1 就会更聪明
比如:rtx4090 48G