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)
相关推荐
DLite16 分钟前
Python静态类型设计:语法割裂的槽点
开发语言·python
2501_9216494916 分钟前
如何获取外汇实时数据:全球货币行情对接指南
后端·python·websocket·金融·区块链
时光Autistic37 分钟前
【环境配置】安装LaTeX并配置到PyCharm使用
ide·python·pycharm·latex
leiming61 小时前
c++ set容器
开发语言·c++·算法
岁岁的O泡奶1 小时前
NSSCTF_crypto_[LitCTF 2024]common_primes
开发语言·python·算法
韩师傅1 小时前
从随叫随到到规范配送:现代物流系统与 REST API 的登场
后端·python·全栈
阿拉丁的梦1 小时前
五种翻译--mo字典翻译任何blender插件的插件
python·blender
资生算法程序员_畅想家_剑魔1 小时前
Java常见技术分享-28-事务安全-事务日志-事务日志流程
java·开发语言
玄同7651 小时前
Python 系统编程双雄:sys 与 os 模块深度实践指南
开发语言·数据库·人工智能·windows·笔记·python·microsoft
Edward.W1 小时前
Python实现文字转ASCII艺术字生成器
开发语言·python