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

相关推荐
憋废话_开码7 分钟前
phpstrom 配置调试 php 项目全流程,弄清一些概念
开发语言·php
ou.cs8 分钟前
c# 企业级ADB通信示例
开发语言·adb·c#
孙桂月36 分钟前
Python爬取数据(二)
开发语言·python
白白糖38 分钟前
组合与括号生成(回溯)
python·算法·力扣
chxin140161 小时前
PyTorch 学习笔记
pytorch·笔记·python
好奇的菜鸟1 小时前
Scoop + Kotlin 极简开发环境搭建指南
android·开发语言·kotlin
滴答滴答嗒嗒滴1 小时前
Python 小练习系列 | Vol.14:掌握偏函数 partial,用函数更丝滑!
开发语言·python
leluckys1 小时前
swift-oc和swift block和代理
开发语言·ios·swift
魂兮-龙游2 小时前
C语言:字符串处理函数strstr分析
c语言·开发语言·数据处理·字符串处理
来自星星的坤2 小时前
Spring Boot 邮件发送配置遇到的坑:解决 JavaMailSenderImpl 未找到的错误
java·开发语言·spring boot·后端·spring