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)
相关推荐
Hgfdsaqwr4 分钟前
Python在2024年的主要趋势与发展方向
jvm·数据库·python
lly20240628 分钟前
jQuery Mobile 表格
开发语言
一晌小贪欢30 分钟前
Python 测试利器:使用 pytest 高效编写和管理单元测试
python·单元测试·pytest·python3·python测试
小文数模30 分钟前
2026年美赛数学建模C题完整参考论文(含模型和代码)
python·数学建模·matlab
惊讶的猫32 分钟前
探究StringBuilder和StringBuffer的线程安全问题
java·开发语言
Halo_tjn38 分钟前
基于封装的专项 知识点
java·前端·python·算法
Hgfdsaqwr1 小时前
掌握Python魔法方法(Magic Methods)
jvm·数据库·python
weixin_395448911 小时前
export_onnx.py_0130
pytorch·python·深度学习
m0_748233171 小时前
30秒掌握C++核心精髓
开发语言·c++
s1hiyu1 小时前
使用Scrapy框架构建分布式爬虫
jvm·数据库·python