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)
相关推荐
Zane199420 分钟前
create_task 和直接 await 到底有什么不一样?asyncio 的 Task、gather 与并发数量控制
后端·python
李可以量化22 分钟前
Redis 从了解到精通(四・下):分区技术原理与选型全解析
python
Python私教33 分钟前
创业团队做管理系统,别先堆页面:我把 14 个问题做成了需求门禁
后端·python·架构
Logintern0940 分钟前
[Matlab] 遗传算法求解TSP入门
开发语言·matlab
云半S一41 分钟前
Python学习总结
python·学习·学习分享
苏子寒44 分钟前
Nano-VLLM全代码解析笔记(6)-embed_head和linear
pytorch·笔记·python·机器学习·ai·nlp·vllm
JTaoX1 小时前
PyCharm 连接本地虚拟机完整指南
ide·python·pycharm
深蓝电商API1 小时前
AES 加密逆向思路
爬虫·aes 加密
Hi_Amos1 小时前
记一次 yfinance 源码调试:SOCKS5 代理下 Chart API 正常,历史数据却一直超时
python·k线·yfinance
练习时长两年半的RL练习生1 小时前
与AI对话后对 Actor-Critic 中 TD Target 的 a‘ 来源总结
开发语言·人工智能·php