欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 旅游 > python爬虫简易入门示例

python爬虫简易入门示例

2024/10/23 23:21:01 来源:https://blog.csdn.net/yan1915766026/article/details/143052822  浏览:    关键词:python爬虫简易入门示例

版本环境

  • win11
  • python 3.12.4

目标:爬取https://gitee.com/explore的列表内容,并写入txt文本

效果

在这里插入图片描述
在这里插入图片描述

开始

1.安装依赖

pip install requests beautifulsoup4

2.编写代码,如下,详见注释

import requests
from bs4 import BeautifulSoupdef get_url_nfo(web_url):response = requests.get(web_url)if response.status_code == 200:# 手动设置响应的编码,可能会有乱码response.encoding = 'utf-8'soup = BeautifulSoup(response.text, "html.parser")# 查找所有 class 为 nav-item-text 的元素class_items = soup.find_all(class_='project-namespace-path')# 提取并打印每个元素的文本内容nav_item_texts = [item.get_text(strip=True) for item in class_items]print('nav_item_texts', nav_item_texts)write_str = str(nav_item_texts).replace(',', '\n')print('已获取内容,处理格式-----------')print('write_str', write_str)write_content_into_txt(write_str)title = soup.titleprint(f'页面标题: {title}')# print('soup.text', soup.text)# print('soup', soup)else:print('请求失败,状态码:', response.status_code)def write_content_into_txt(content):try:with open('python爬取gitee.txt', 'w', encoding='utf-8') as file:file.write(content)print('内容已写入文件')except Exception as e:print(f'写入文件时发生错误: {e}')# 请求url
url = "https://gitee.com/explore"
get_url_nfo(url)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com