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)
相关推荐
vx-程序开发2 小时前
springboot旅游推介平台---附源码24175
java·spring boot·python·spring cloud·eclipse·django·idea
心运软件2 小时前
基于深度学习的宝石图像分类系统
人工智能·python·深度学习·机器学习·分类·数据挖掘
格林威2 小时前
多相机并行采图最佳实践:Task.WhenAll + 异常处理 + 资源释放
开发语言·人工智能·数码相机·计算机视觉·c#·视觉检测·机器视觉
djjjx.2 小时前
【 C++ 】多态
开发语言·c++·多态
一木 之林2 小时前
AI实战 : Numpy图像处理与深度学习框架
python
c_lb72882 小时前
零基础选策略工具,先分清三件事
人工智能·python
夜雪一千2 小时前
Python如何使用XPath定位没有特征的元素?无id、无class通用定位技巧
开发语言·python
艾莉丝努力练剑3 小时前
【QT:解决问题】Qt5Core.dll:无法定位程序输入点
java·开发语言·qt·学习·面试
流浪0013 小时前
Python 基础语法(一):常量、变量、输入输出与运算符
开发语言·python
光影少年3 小时前
react离线缓存、图片缓存方案
开发语言·前端·javascript·react native·react.js·缓存·前端框架