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)
相关推荐
忧郁的橙子.2 分钟前
26期_01_Pyhton判断语句
python
快乐小胡!7 分钟前
【自动化测试】Selenium选择/定位元素的基本方法
python·selenium·测试工具
余醉 | dtminer10 分钟前
R语言常见新手问题
开发语言·r语言
それども14 分钟前
为什么要加@ResponseBody
java·开发语言·spring boot
一只专注api接口开发的技术猿25 分钟前
微服务架构下集成淘宝商品 API 的实践与思考
java·大数据·开发语言·数据库·微服务·架构
高洁0126 分钟前
数字孪生与数字样机的技术基础:建模与仿真
python·算法·机器学习·transformer·知识图谱
喵手27 分钟前
Python爬虫零基础入门【第二章:网页基础·第4节】新手最常栽的坑:编码、时区、空值、脏数据!
爬虫·python·python爬虫实战·python爬虫工程化实战·python爬虫零基础入门·python爬虫编码时区·爬虫编码时区
被星1砸昏头32 分钟前
C++中的享元模式
开发语言·c++·算法
2501_9444241235 分钟前
Flutter for OpenHarmony游戏集合App实战之记忆翻牌配对消除
android·java·开发语言·javascript·windows·flutter·游戏
m0_7482404441 分钟前
Laravel5.6核心更新全解析
开发语言·php