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)
相关推荐
geovindu12 分钟前
rust: Template Method Pattern
开发语言·后端·设计模式·rust·行为模式·模板方法模
MoRanzhi120312 分钟前
第4篇 · 使用 PyQt5 实现 2048:平滑动画与性能优化
python·性能优化·qtimer·pyqt5·qpainter·gui动画·2048游戏
海姐软件测试32 分钟前
Python 自动化与 AI 结合:基于 Jenkins 的回归验证实践
人工智能·python·自动化
傻啦嘿哟39 分钟前
百度图片爬虫:爬取海量图片数据,搭建图像识别训练集
爬虫·百度
Haoyunyi39 分钟前
2026年做期货量化,和三年前已经不是一回事了
大数据·人工智能·python·金融·区块链
再__努力1点1 小时前
一个开源的AI边缘计算平台:一个项目把算能、瑞芯微、x86的NPU全打通了
人工智能·python·课程设计·媒体·流媒体
小oo呆1 小时前
【学习心得】Python函数参数中的两个特殊分隔符
开发语言·python
x10n91 小时前
微软 VC++ 运行库合集VCRedistPack
开发语言·c++·microsoft·vc++运行库·dll报错
qz_Serene1 小时前
C++:string(底层,常用接口,具体题目,模拟实现)
开发语言·c++