2024最新LangChain网页数据爬取实战教程
网页数据抓取方面,LangChain 显著降低了入门难度——它内置了可直接调用的工具链,避免重复造轮子。以本次演示的页面爬取为例,就是一项典型应用。
LangChain 官方文档中的网页爬取章节也提供了高质量的参考示例,值得深入研读。
适用场景
批量页面内容采集
RAG 知识库信息检索
实战步骤
需求拆解
从 ceshiren 论坛抓取每条帖子的标题及其对应的 URL。
目标论坛地址:https://ceshiren.com/
实现逻辑
(此处自然衔接核心步骤:加载→解析→分块→提取)
完整代码
# 定义大模型
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613")
# 定义提取方法
def extract(content: str, schema: dict):
from langchain.chains import create_extraction_chain
return create_extraction_chain(schema=schema, llm=llm).invoke(content)
import pprint
from langchain_text_splitters import RecursiveCharacterTextSplitter
def scrape_with_playwright(urls, schema):
# 加载数据
loader = AsyncChromiumLoader(urls)
docs = loader.load()
# 数据转换
bs_transformer = BeautifulSoupTransformer()
# 提取其中的span标签
docs_transformed = bs_transformer.transform_documents(
docs, tags_to_extract=["span"]
)
# 数据切分
splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
chunk_size=1000, chunk_overlap=0)
splits = splitter.split_documents(docs_transformed)
# 因为数据量太大,输入第一片数据使用,传入使用的架构
extracted_content = extract(schema=schema, content=splits[0].page_content)
pprint.pprint(extracted_content)
return extracted_content
urls = ["https://ceshiren.com/"]
schema = {
"properties": {
"title": {"type": "string"},
"url": {"type": "string"},
},
"required": ["title", "url"],
}
extracted_content = scrape_with_playwright(urls, schema=schema)
核心收获
掌握了基于 LangChain 的网页抓取完整流程与关键技术。
通过 Playwright + LangChain 组合,成功从 ceshiren 论坛提取帖子标题与链接。
