要编写一个Python抽奖程序,可以按照以下步骤进行:
- 确定奖品和参与抽奖的人员名单。
- 创建一个列表来存储奖品和参与抽奖的人员名单。
- 编写一个函数来进行抽奖。
- 在函数中,使用random模块的choice方法从参与抽奖的人员名单中随机选择一个中奖者。
- 使用random模块的choice方法从奖品列表中随机选择一个奖品。
- 输出中奖者和奖品信息。
#第一步:确认定抽奖的人员,这里我们选择英雄联盟
#首先要提取英雄联盟的人员名单,这里我们用爬虫
#python程序代码:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from random import randint import time browser = webdriver.Edge() url = 'https://101.qq.com/#/hero' try: browser.get(url) # 等待页面加载完毕(根据实际情况调整) time.sleep(5) # 使用XPath查找所有的英雄元素 hero_elements = browser.find_elements(by=By.XPATH, value='//ul[@class=\'hero-list\']/li') # 随机选择一个英雄元素 selected_hero = hero_elements[randint(0, len(hero_elements) - 1)] hero = selected_hero.text # 将英雄名字写入文件 with open("./名字.txt", 'w', encoding='utf-8') as fp: fp.write(hero) except Exception as e: print(f"An error occurred: {e}") finally: # 关闭浏览器 browser.quit()
#第二步 读取文件,并将文件放入到一个列表中
with open("./名字.txt","r",encoding="utf-8") as pf: hero=pf.read()
#对英雄名进行分割,也可以用正则,转换成列表的形式 hero=hero.split("\n")
#第三步,引用前端框架
from flask import Flask,render_template
app=Flask(__name__)
#第四步,调用app,并写一个抽奖程序
#引用这个框架,然后调用程序中的index的函数,进行输出; @app.route('/index') def index(): #建立文件夹框架的,文件名必须是templates,一定要加S,否则要报错,找不到 return render_template("index.html",hero=hero) # return "hello" @app.route('/choujiang') def choujiang(): n=randint(0,len(hero)-1) return render_template("index.html",hero=hero,h=hero[n]) # return hero[n]
那么我的后端程序就写完了,下面必须配合一个前段的程序才可以;
写一个index 的html页面;
第五步,
#在存储程序的文件夹下面建一个template的文件夹,文件加下写一个index.html的文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!--这个是注释的写法 --> <h4>{{hero}}</h4> <a href="/choujiang">随机抽奖</a></br> <h4>您抽到了:<u>{{h}}</u></h4> </body> </html>
完工,下面我们来实验一下;