爬虫蜘蛛通常用于从网站上抓取数据。Python中有很多库可以用来编写爬虫,其中最常用的是requestsBeautifulSoup。下面是一个简单的爬虫蜘蛛示例,用于抓取网页上的标题和链接:


python复制代码

import requests
from bs4 import BeautifulSoup
def get_page(url):
try:
response = requests.get(url)
response.raise_for_status()
return response.text
except requests.RequestException as e:
print(e)
def parse_page(html):
soup = BeautifulSoup(html, 'html.parser')
# 获取所有标题和链接
titles = soup.find_all('h1')
links = soup.find_all('a')
# 打印标题和链接
for title in titles:
print(title.get_text())
for link in links:
print(link.get('href'))
if __name__ == '__main__':
url = 'http://example.com' # 要抓取的网页地址
html = get_page(url)
if html:
parse_page(html)

在这个示例中,我们首先使用requests库向指定的URL发送GET请求,并获取返回的HTML内容。然后,我们使用BeautifulSoup库解析HTML,并使用选择器找到所有的标题和链接。最后,我们将标题和链接打印到控制台上。

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐