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)
相关推荐
BU摆烂会噶1 分钟前
【LangGraph】House_Agent 实战(五):持久化、流式输出与部署
人工智能·python·架构·langchain·人机交互
L_09076 分钟前
【C++】面向对象三大特性之多态
开发语言·c++
少年强则国强9 分钟前
安装配置Claude
python
threelab9 分钟前
Three.js 银河星系效果 | 三维可视化 / AI 提示词
开发语言·javascript·人工智能
程序员敲代码吗10 分钟前
探索JavaScript对象创建的灵活方式
开发语言·javascript·ecmascript
机汇五金_11 分钟前
深圳电脑机箱厂家
python
FlyWIHTSKY13 分钟前
Next.js中客户端组件和服务端组件
开发语言·javascript·ecmascript
天若有情67313 分钟前
轻量级状态事件总线 eventbusx-js 开源使用教程
开发语言·javascript·npm·开源·事件·事件总线
XMYX-016 分钟前
36 - Go exec 执行命令
开发语言·golang
寻道码路16 分钟前
LangChain4j Java AI 应用开发实战(二):大模型参数调优实战:Temperature、TopP、MaxTokens 深度解析
java·开发语言·人工智能·aigc