Crawl4AI 基础爬取指南——基本使用

115
0
0
2024-11-11

Crawl4AI 基础爬取指南——基本使用

本指南涵盖了使用 Crawl4AI 进行网络爬取的基础知识。你将学习如何设置爬虫,发出第一个请求,并理解响应内容。

基本使用

这是爬取网页最简单的方式:

python
import asyncio
from crawl4ai import AsyncWebCrawler

async def main():
    async with AsyncWebCrawler() as crawler:
        result = await crawler.arun(url="https://example.com") 
        print(result.markdown)  # 打印干净的 Markdown 内容

if __name__ == "__main__":
    asyncio.run(main())

理解响应

arun() 方法返回一个 CrawlResult 对象,包含几个有用的属性。这里是一个快速概览(详见 CrawlResult):

python
result = await crawler.arun(url="https://example.com")

# 不同内容格式
print(result.html)         # 原始 HTML
print(result.cleaned_html) # 清理后的 HTML
print(result.markdown)     # Markdown 版本
print(result.fit_markdown) # Markdown 中最相关的部分内容

# 检查成功状态
print(result.success)      # 如果爬取成功则为 True
print(result.status_code)  # HTTP 状态码(例如:200, 404)

# 访问提取的媒体和链接
print(result.media)        # 找到媒体的字典(图片、视频、音频)
print(result.links)        # 内部和外部链接的字典

添加基本选项

使用这些常见选项自定义你的爬取:

python
result = await crawler.arun(
    url="https://example.com", 
    word_count_threshold=10,        # 每个内容块的最小字数
    exclude_external_links=True,    # 移除外部链接
    remove_overlay_elements=True,   # 移除弹出/模态窗口
    process_iframes=True            # 处理 iframe 内容
)

错误处理

始终检查爬取是否成功:

python
result = await crawler.arun(url="https://example.com") 
if not result.success:
    print(f"爬取失败: {result.error_message}")
    print(f"状态码: {result.status_code}")

日志记录和调试

启用详细模式以获取详细日志:

python
async with AsyncWebCrawler(verbose=True) as crawler:
    result = await crawler.arun(url="https://example.com") 

完整示例

这是一个更全面的示例,展示了常见的使用模式:

python
import asyncio
from crawl4ai import AsyncWebCrawler

async def main():
    async with AsyncWebCrawler(verbose=True) as crawler:
        result = await crawler.arun(
            url="https://example.com", 
            # 内容过滤
            word_count_threshold=10,
            excluded_tags=['form', 'header'],
            exclude_external_links=True,

            # 内容处理
            process_iframes=True,
            remove_overlay_elements=True,

            # 缓存控制
            bypass_cache=False  # 如果可用则使用缓存
        )

        if result.success:
            # 打印干净的内容
            print("内容:", result.markdown[:500])  # 前 500 个字符

            # 处理图片
            for image in result.media["images"]:
                print(f"找到图片: {image['src']}")

            # 处理链接
            for link in result.links["internal"]:
                print(f"内部链接: {link['href']}")

        else:
            print(f"爬取失败: {result.error_message}")

if __name__ == "__main__":
    asyncio.run(main())