python爬虫简易入门示例

版本环境

  • win11
  • python 3.12.4

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

效果


开始

1.安装依赖

bash 复制代码
pip install requests beautifulsoup4

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

python 复制代码
import requests
from bs4 import BeautifulSoup


def 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.title

        print(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)
相关推荐
.道阻且长.8 分钟前
C++ string 操作指南:接口解析
java·c语言·开发语言·c++
蚰蜒螟10 分钟前
Java 对象的内存密语:从字段偏移量计算到 Unsafe 访问的完整链路
java·开发语言
2601_9516457820 分钟前
如何优雅地使用c语言编写爬虫
c语言·爬虫·网络请求·字符串处理·cspider
星辰_mya27 分钟前
CountDownLatch深度解析
java·开发语言·后端·架构
laplaya31 分钟前
使用 vcpkg 管理 C++ 项目中的依赖
开发语言·c++
feixing_fx42 分钟前
选择器的威力——深入理解优先级计算与层叠规则
开发语言·前端·css·前端框架·html
极光代码工作室1 小时前
基于深度学习的手写数字识别系统
人工智能·python·深度学习·神经网络·机器学习
6v6-博客1 小时前
C语言字符串中空格的表示方法
c语言·开发语言
geovindu1 小时前
python: speech to text offline
开发语言·python·语音识别
AI创界者1 小时前
告别云端限制!Sulphur 2 本地文生视频/图生视频整合包,本地部署,解压即用,保姆级部署与工作流实战
人工智能·python·aigc·音视频