用python写个爬虫蜘蛛

爬虫蜘蛛通常用于从网站上抓取数据。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,并使用选择器找到所有的标题和链接。最后,我们将标题和链接打印到控制台上。

相关推荐
IVEN_1 天前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang1 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮1 天前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling1 天前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮1 天前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽1 天前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健2 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞2 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽2 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers