1. 背景
最近本qiang~關(guān)注了一個(gè)開源項(xiàng)目Scrapegraph-ai,是關(guān)于網(wǎng)頁爬蟲結(jié)合LLM的項(xiàng)目,所以想一探究竟,畢竟當(dāng)下及未來,LLM終將替代以往的方方面面。
這篇文章主要介紹下該項(xiàng)目,并基于此項(xiàng)目實(shí)現(xiàn)一個(gè)demo頁面,頁面功能是輸入一個(gè)待爬取的網(wǎng)頁地址以及想要從網(wǎng)頁中抽取的內(nèi)容,最后點(diǎn)擊按鈕實(shí)現(xiàn)網(wǎng)頁抓取及解析。
2. 模塊簡介
2.1 Scrapegraph-ai

該項(xiàng)目是一個(gè)網(wǎng)頁爬蟲的python包,使用LLM和直接圖邏輯(direct
graph logic)來為網(wǎng)頁和本地文檔(XML, HTML, JSON)創(chuàng)建爬取管道(pipeline)。
2.2 GPT-3.5免費(fèi)申請,且國內(nèi)可訪問
GPT3.5-Turbo免費(fèi)申請可以在開源項(xiàng)目GPT_API_free進(jìn)行訪問,其中該項(xiàng)目有免費(fèi)申請的地址,以及網(wǎng)頁插件、桌面應(yīng)用安裝等教程,在日志工作學(xué)習(xí)中,使用起來非常絲滑~
其次,國內(nèi)訪問gpt3.5可以基于該項(xiàng)目提供的代理:https://api.chatanywhere.tech/v1來實(shí)現(xiàn)訪問。
3. 實(shí)戰(zhàn)
3.1 安裝第三方包
# 網(wǎng)頁開發(fā)包,和Gradio類似
pip install streamlit
# 爬蟲相關(guān)包
pip install playwright
playwright install
playwright install-deps # 安裝依賴
3.2 設(shè)置gpt3.5代理環(huán)境變量
import os
os.environ['OPENAI_API_BASE'] = 'https://api.chatanywhere.tech/v1'
OPEN_API_KEY = 'sk-xxxxx'
3.3 創(chuàng)建網(wǎng)頁元素
import streamlit as st
st.title('網(wǎng)頁爬蟲AI agent')
st.caption('該app基于gpt3.5抓取網(wǎng)頁信息')
url = st.text_input('屬于你想抓取的網(wǎng)頁地址URL')
user_prompt = st.text_input('輸入你想要從該網(wǎng)頁獲取知識(shí)的prompt')
3.4 基于scrapegraph-ai包構(gòu)建圖配置以及創(chuàng)建圖邏輯
from scrapegraphai.graphs import SmartScraperGraph
# 圖配置信息,默認(rèn)調(diào)用gpt3.5,其次embedding模型未設(shè)置,但閱讀源碼后,可以發(fā)現(xiàn)默認(rèn)走的是openai的embedding模型
graph_config = {
??? 'llm': {
??????? 'api_key':? OPEN_API_KEY,
??????? 'model':? 'gpt-3.5-turbo',
??????? 'temperature': 0.1
??? }
}
# 創(chuàng)建直接圖邏輯
smart_scraper_graph = SmartScraperGraph(
??? prompt=user_prompt, #用戶輸入的prompt
??? source=url, #用戶輸入的url
??? config=graph_config
)
# 增加一個(gè)按鈕進(jìn)行爬取、解析及頁面渲染
if st.button('爬取'):
??? result =? smart_scraper_graph.run()
??? st.write(result)
3.5 運(yùn)行啟動(dòng)
streamlit run scrape_web_openai.py
3.6 底層原理
通過研讀SmartScraperGraph源碼,底層直接圖邏輯的原理如下圖所示。分為抓取、解析、RAG、答案生成,并默認(rèn)以json格式輸出

4. 效果
4.1 新聞?lì)?/h2>
網(wǎng)址:ps://news.sina.com.cn/w/2024-05-20/doc-inavwrxq4965190.shtml

4.2 公眾號(hào)
https://mp.weixin.qq.com/s/rFYXKiedqmVo5URDxlbHzA

針對一些簡單的網(wǎng)頁如新聞網(wǎng)頁等,可以正常爬取,但響應(yīng)時(shí)間在10s以上,針對一些復(fù)雜的頁面,如包含鑒權(quán)、反爬機(jī)制等,可能無法正常爬取。
5. 總結(jié)
一句話足矣~
本文主要是通過Scrapegraph-ai集成gpt3.5實(shí)現(xiàn)一個(gè)簡單的網(wǎng)頁爬取并解析的demo應(yīng)用,其中涉及到gpt3.5免費(fèi)申請,Scrapegraph-ai底層原理簡介,demo應(yīng)用源碼等。
之后會(huì)寫一篇關(guān)于Qwen7B和BGE的相似度模型,與Scrapegraph-ai集成的demo應(yīng)用,敬請期待~
6. 參考
1. Scrapegraph-ai: https://github.com/VinciGit00/Scrapegraph-ai
2. GPT_API_free:https://github.com/chatanywhere/GPT_API_free