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)
相关推荐
jnrjian8 分钟前
delete file shell 让 AI 写脚本
服务器·开发语言
傅科摆 _ py22 分钟前
DP,贪心,堆和栈,二分力扣复习
开发语言·python·算法
kiracrimson29 分钟前
栈与队列容器:适配器、deque 与 priority_queue
开发语言·c++·适配器模式
北冥you鱼42 分钟前
Go 语言 CRUD 实战:从接口设计到真实业务场景
开发语言·后端·golang
吴名氏.1 小时前
Java转AI Agent教程(第一周)让模型先跑起来
人工智能·python·ai·ai agent
郭小李1 小时前
springmvc 拦截器
java·开发语言·前端
web打印社区1 小时前
Chrome-kiosk-printing能上生产吗
开发语言·前端·javascript·chrome·websocket
大风起兮云飞扬丶1 小时前
Java——日期类
java·开发语言
Wang's Blog1 小时前
Java 项目实战:交友项目 - 联系人管理需求分析
java·开发语言·交友
第404号工位1 小时前
离职退电脑前别只点“清空回收站”!手把手教你彻底抹除凭证与数字痕迹
linux·python·架构