在上一篇文章中,我们讨论了暗网、它是如何工作的、我们如何访问它以及从中收集数据的方法。我们还探讨了我们可能面临的一些挑战,例如旨在阻止从论坛和市场收集数据的复杂验证码和反抓取机制。不幸的是,这些障碍仍然存在,虽然我们构建了一个简单的工具来帮助收集信息,但这还不够。
但是,借助我们将在本博客中介绍的技术,我们不仅可以避免编写数百行代码,还可以克服我们过去面临的一些挑战。借助 Llama,我们将能够收集、处理、分析甚至讨论动态数据。
你能相信吗?太神奇了,对吧?让我们开始吧!
与往常一样,我们构建强大应用程序的首选工具是
Python
🐍!
首先,让我们探索必要的要求和依赖关系 .
#requirements.txt streamlit langchain langchain_ollama selenium beautifulsoup4
Streamlit 允许快速创建交互式 Web 应用程序,LangChain 提供了一个框架,用于使用语言模型构建工作流,用于问答和摘要等任务,LangChain_Ollama 支持与 Ollama 模型集成,而 Selenium 自动执行浏览器操作以测试和抓取动态页面,BeautifulSoup4 解析 HTML 和 XML 中的数据。
我建议创建一个 Python 虚拟环境,以保持我们所有的项目需求井井有条,方法如下
python3 -m venv<venv_name>
然后使用
<venv_name>Scriptsactivate
现在,让我们创建一个名为 的文件,并使用以下命令安装所有需求:
requirements.txt
pip3 install -r requirements.txt
一切准备就绪后,我们将创建主 Python 文件来构建应用程序的界面,因此我们将使用 Streamlit :
#main.py import streamlitas st st.title ("OiQ Scraper") url = st.text_input("Search For Website")
我们可以添加一些独特的东西,例如横幅
st.markdown( """ ``` _________________/\\___________________/\_________________ _______________/\///\______________/\\/\\______________ _____________/\/__///\___/\___/\//////\____________ ____________/\______//\_///___/\______//\___________ ___________/\_______/\__/\_//\______/\____________ ___________//\______/\__/\__///\\/\\/_____________ ____________///\__/\____/\____////\//_______________ ______________///\\/_____/\_______///\\\____________ ________________/////_______///__________//////_____________ ``` """, unsafe_allow_html=True )
结果应该是在运行
streamlitmain.py--server.port <Port>
现在,让我们继续构建我们的抓取函数。
#scrape.py import selenium.webdriveras webdriver from selenium.webdriver.firefox.serviceimport Service from selenium.webdriver.firefox.optionsimport Options defscrapWebsite(website): options = Options() #headless Browsing options.add_argument("--headless") # Path to the firefox WebDriver and Profile options.profile =r" FireFox Profile " firefoxDriver_path ="./geckodriver.exe" service = Service(firefoxDriver_path) driver = webdriver.Firefox(service=service, options=options) try: driver.get(website) print("page loaded ..") html = driver.page_source return html except Exceptionas e: print(f"An error occurred:{str(e)}")
要检索您的 Firefox 配置文件路径,只需打开 Firefox,在地址栏中输入,然后找到您正在使用的路径,然后复制 根目录路径 .
about:profiles
从导入必要的模块开始 :用于浏览器自动化和自定义浏览器设置。
selenium.webdriver
Options
该函数在无头模式下初始化 Firefox,这意味着它在运行时不会打开可见的浏览器窗口。
scrapWebsite(website)
然后,使用此路径设置实例,并使用指定的服务和选项创建 Firefox WebDriver 实例。
Service
然后,该函数会尝试打开指定的 URL。如果成功,它将检索页面的 HTML 源代码并返回它。如果在加载过程中发生错误,则会捕获并打印异常。
website
总之,此代码旨在在无头 Firefox 中加载网站并检索 HTML 源代码 。
明白了!现在我们已经加载了网站,让我们创建一个函数来使用 BeautifulSoup 从中提取数据。
#scrape.py .. defextract_body_content(html_content): soup = BeautifulSoup(html_content,"html.parser") body_content = soup.body if body_content: returnstr(body_content) return"Nothing"
该函数从 HTML 页面中提取标记中的主要内容。
extract_body_content
<body>
它采用作为输入,使用 BeautifulSoup 对其进行解析,然后找到标签。如果标签存在,则以字符串形式返回其内容;否则,它将返回 。
html_content
<body>
<body>
"Nothing"
此功能可用于隔离网页的主要内容 。
提取数据后,我们需要对其进行清理并仅保留相关信息。
#scrape.py .. defclean_body_content(body_content): soup = BeautifulSoup(body_content,"html.parser") for script_or_stylein soup(["script","style"]): script_or_style.extract() cleaned_content = soup.get_text(separator="n") cleaned_content ="n".join( line.strip()for linein cleaned_content.splitlines()if line.strip() ) return cleaned_content
该函数旨在过滤掉不必要的元素,并仅保留 HTML 正文内容中的相关文本。
clean_body_content
首先,它作为输入并使用 BeautifulSoup 对其进行解析。它删除了所有 and 标签,以消除通常不相关的 JavaScript 和 CSS 内容。
body_content
<script>
<style>
然后,它检索剩余的文本并通过去除多余的空格来格式化它。它通过将文本拆分为行、删除空行以及使用换行符和可读文本连接已清理的行来实现此目的。
split_dom_content ( ) 函数将大型 HTML 或文本内容dom_content分解为较小的、可管理的块,每个块具有由 max_length 指定的最大长度。
#scrape.py .. defsplit_dom_content(dom_content, max_length=6000): return [ dom_content[i : i + max_length]for iinrange(0,len(dom_content), max_length) ]
它通过以 的增量迭代来实现这一点,创建一个列表,其中每个元素都是不超过 的切片。
dom_content
max_length
dom_content
max_length
此功能在分批处理长文本数据时特别有用,例如在处理或分析有限大小的段中的内容时。
现在让我们将创建的函数集成到 main 函数中,并按顺序调用它们来处理网页内容。
#main.py .. from Scrapeimport( scrapWebsite , split_dom_content , clean_body_content , extract_body_content ) st.title("AI Scraper") url = st.text_input("Search For Website") if st.button("Start Scraping"): if url : st.write("Scraping...") result = scrapWebsite(url) # print(result) bodyContent = extract_body_content(result) cleanedContent = clean_body_content(bodyContent) st.session_state.dom_content = cleanedContent with st.expander ("View All Content") : st.text_area("Content" , cleanedContent, height=300)
通过创建一个简单的 Streamlit 界面来抓取和显示网页内容,用户可以在文本输入字段中输入 URL。
st.text_input
单击“开始抓取”按钮时,它会检查 URL 字段是否具有内容 ,如果是,则通过调用 来启动抓取过程,该调用将检索原始 HTML。然后,该函数会隔离主要内容,并过滤掉不必要的元素,例如脚本和样式。
scrapWebsite(url)
extract_body_content
<body>
clean_body_content
清理后的内容存储在 中以实现会话持久性。最后,文本区域显示已清理的内容,允许用户查看提取的文本。
st.session_state.dom_content
到目前为止,我们在创建网络爬虫和从目标网站提取所有数据方面做得很好。
我们已经成功构建了我们的网络爬虫,从我们的目标网站中提取了主要内容,甚至清理了数据以专注于相关信息。我们现在有一个工具,只需单击几下即可动态检索和组织网页内容。
我们现在正在继续集成 Llama 进行内容分析。
#main.py .. if"dom_content"in st.session_state: parse_description = st.text_area("Describe what's in Your Mind ..'") if st.button("Parse Content"): if parse_description: st.write("Parsing the content...") # Parse the content with Ollama dom_chunks = split_dom_content(st.session_state.dom_content)
首先,我们检查 中是否有可用,这表明我们已经抓取了数据以供处理。然后,我们显示一个文本区域,供用户输入他们想要分析的内容的描述。
dom_content
st.session_state
单击Parse Content 按钮时,我们确保用户已输入描述并继续解析内容。
我们将抓取的数据分成更小的块,以使 Llama 更容易处理。
split_dom_content
这种集成将使我们能够交互式地分析和解释抓取的内容。
要将 Llama 集成到我们的代码中,我们可以创建一个名为 example 的新 Python 文件,并导入必要的库以连接到 Llama 并与之交互。
Ollama.py
#Ollama.py from langchain_ollamaimport OllamaLLM from langchain_core.promptsimport ChatPromptTemplate
OllamaLLM允许与 Ollama 语言模型连接和交互以执行文本处理和分析等任务,并帮助创建基于结构化聊天的提示模板以发送到语言模型。
ChatPromptTemplate
#Ollama.py .. model = OllamaLLM(model="llama3")
它创建类的实例,该实例连接到 llama3 模型。
OllamaLLM
然后我们需要导入这个模板:
#Ollama.py .. template = ( "You are tasked with extracting specific information from the following text content: {dom_content}. " "Please follow these instructions carefully: nn" "1. **Extract Information:** Only extract the information that directly matches the provided description: {parseDescription}. " "2. **No Extra Content:** Do not include any additional text, comments, or explanations in your response. " "3. **Empty Response:** If no information matches the description, return an empty string ('')." "4. **Direct Data Only:** Your output should contain only the data that is explicitly requested, with no other text." )
通过为 Ollama 模型创建带有明确说明的模板,它告诉模型根据 .
dom_content
parseDescription
指示模型仅返回与描述匹配的信息,避免添加额外的详细信息,如果没有匹配项,则返回空字符串,并且仅提供请求的数据。
这可确保提取集中且准确。
#Ollama.py .. defparseUsingOllama (domChunks , parseDescription) : prompt = ChatPromptTemplate.from_template(template) chain = prompt | model finalResult = [] for counter , chunkinenumerate (domChunks , start=1) : result = chain.invoke( {"dom_content": chunk ,"parseDescription": parseDescription} ) print(f"Parsed Batch{counter} of{len(domChunks)}") finalResult.append(result) return"n".join(finalResult)
该函数采用两个输入: (这是内容的一部分)和 (告知要提取的信息)。它会创建一个包含模型说明的提示,然后逐个处理每个内容块。
parseUsingOllama
domChunks
parseDescription
对于每个数据块,该函数要求模型根据描述提取相关信息。
它存储结果并显示正在处理的块。最后,它将返回合并到一个字符串中的所有结果。
此功能通过将大型内容分解为较小的部分,可以更轻松地从大型内容中提取特定细节。
要使用 Llama 模型,我们需要从 Ollama 官方网站安装它,这里有一个有用的指南可以帮助您完成安装和运行过程。
如果您遇到任何问题,请查看 GitHub 存储库以获取其他有用的命令和详细说明。
要将 Ollama 解析函数重新集成到我们的主应用程序中,我们需要从文件中导入函数。
parseUsingOllama
parseOllama
#main.py .. from parseOllamaimport parseUsingOllama
导入后,我们可以在 main 函数中调用该函数,以使用提供的描述处理内容
parseUsingOllama
#main.py .. parsed_result = parseUsingOllama(dom_chunks, parse_description) st.write(parsed_result)
现在,剩下的唯一事情就是运行我们的程序并查看它的运行情况!
如果一切看起来都不错,我们就会知道我们的程序已经准备好并按计划运行!
总之,我们创建了一个简化的 Web 爬虫,它可以从目标网站检索、清理和显示相关内容。然后,我们通过 Ollama API 集成了 Llama,以帮助我们使用自定义模板从抓取的数据中分析和提取特定信息。通过将内容分解为可管理的块并应用明确的说明,我们确保根据用户的输入仅显示最相关的数据。
原文始发于微信公众号(安全狗的自我修养):使用 AI 进行暗网抓取:工具、技术和挑战
- 左青龙
- 微信扫一扫
-
- 右白虎
- 微信扫一扫
-
评论