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)
相关推荐
freyazzr13 分钟前
C++八股 | Day3 | 智能指针 / 内存管理 / 内存分区 / 内存对齐
开发语言·c++
序属秋秋秋19 分钟前
《C++初阶之入门基础》【普通引用 + 常量引用 + 内联函数 + nullptr】
开发语言·c++·笔记
星辰离彬20 分钟前
Java 高级泛型实战:8 个场景化编程技巧
java·开发语言·后端·程序人生
纨妙20 分钟前
python打卡day47
开发语言·python
ghost14322 分钟前
C#学习第29天:表达式树(Expression Trees)
开发语言·c#
Auscy27 分钟前
JavaScript 数组学习总结
开发语言·javascript·学习
虾球xz28 分钟前
CppCon 2015 学习:Transducers, from Clojure to C++
开发语言·c++·学习
不二狗1 小时前
每日算法 -【Swift 算法】电话号码字母组合
开发语言·算法·swift
张哈大1 小时前
【 java 虚拟机知识 第一篇 】
java·开发语言·jvm·笔记·缓存
沉到海底去吧Go2 小时前
【PDF识别改名】PDF指定区域OCR识别重命名工具使用教程和注意事项
python·pdf·ocr