用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,并使用选择器找到所有的标题和链接。最后,我们将标题和链接打印到控制台上。

相关推荐
知白守黑2671 分钟前
docker网络
开发语言·php
细节控菜鸡4 分钟前
【2025最新】ArcGIS for JS 范围裁剪(只保留特定区域显示),实现精准地理范围聚焦
开发语言·javascript·arcgis
CodeCraft Studio11 分钟前
Excel处理控件Aspose.Cells教程:使用 Python 将 HTML 转换为 Excel
python·html·excel·aspose·aspose.cells·html转excel
一根甜苦瓜19 分钟前
Go语言Slice的一道骚题
开发语言·后端·golang
驰羽26 分钟前
[GO]Go语言泛型详解
开发语言·golang·xcode
NPE~26 分钟前
[手写系列]Go手写db — — 第五版(实现数据库操作模块)
开发语言·数据库·后端·golang·教程·手写系列·手写数据库
润 下28 分钟前
C语言——深入解析C语言指针:从基础到实践从入门到精通(二)
c语言·开发语言·经验分享·笔记·学习·程序人生
王中阳Go35 分钟前
Python 的 PyPy 能追上 Go 的性能吗?
后端·python·go
Goboy43 分钟前
控制仙术流程 - 抉择与循环的艺术
后端·python
布伦鸽1 小时前
C# WPF DataGrid使用Observable<Observable<object>类型作为数据源
开发语言·c#·wpf