Python学习
·
开发语言都是相通的,如果你有Java或者C等经验,学习起来会得心应手;
一、学习参考
学习链接:https://www.runoob.com/python3/python3-tutorial.html
二、爬虫(2025-02-13)
爬取王者荣耀头像,代码如下(刚开始学,可能代码不是那么好):
import os
import requests
from bs4 import BeautifulSoup
import logging
# 设置日志
logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')
# 创建保存图片的文件夹
save_folder = 'hero_avatars'
if not os.path.exists(save_folder):
os.makedirs(save_folder)
# 王者荣耀英雄列表URL
url = 'https://pvp.qq.com/web201605/herolist.shtml'
try:
# 发送HTTP请求
response = requests.get(url)
response.raise_for_status()
# 使用BeautifulSoup解析网页
soup = BeautifulSoup(response.text, 'html.parser')
# 找到所有英雄的div
# heroes = soup.find_all('div', class_='herolist-item')
heroes = soup.find_all('li')
for hero in heroes:
try:
# 获取英雄名称
# hero_name = hero.find('a')['href'].split('/')[-1].split('.')[0]
hero_name = hero.find('a').text.strip()
decoded_text = hero_name.encode('latin1').decode('gb18030')
# 获取英雄头像URL
avatar_url = hero.find('img')['src']
# 发送HTTP请求获取头像图片
avatar_response = requests.get("https:" + avatar_url)
avatar_response.raise_for_status()
# 保存头像图片
with open(os.path.join(save_folder, f'{decoded_text}.jpg'), 'wb') as f:
f.write(avatar_response.content)
except Exception as e:
logging.error(f"获取{decoded_text}头像失败: {e}")
print("所有头像图片已成功下载并保存到本地。")
except requests.exceptions.RequestException as e:
logging.error(f"HTTP请求错误: {e}")
except Exception as e:
logging.error(f"其他错误: {e}")
下载的头像保存在python同级目录:hero_avatars下;
三、简单的Web开发
使用FastAPI,FastAPI 是一个用 Python 写后端接口(API) 的现代 Web 框架;
一个简单的demo代码:
from fastapi import FastAPI
app = FastAPI()
@app.get("/hello")
def hello():
return {"message": "Hello World"}
启动
FastAPI 不是用 python app.py(app.py为文件名) 直接跑的,而是用 ASGI 服务器 uvicorn。
所以需要在Terminal中,输入下面的命令:
uvicorn main:app --reload --port 9000
当然可以不指定port,默认:8000:
uvicorn main:app --reload
访问
http://127.0.0.1:9000/hello
openEuler 是由开放原子开源基金会孵化的全场景开源操作系统项目,面向数字基础设施四大核心场景(服务器、云计算、边缘计算、嵌入式),全面支持 ARM、x86、RISC-V、loongArch、PowerPC、SW-64 等多样性计算架构
更多推荐

所有评论(0)