实现购物系统。
数据:
a. 编写一级菜单并实现功能导航
1)用户注册(用户名不能重复)、两次密码验证)
2)用户登录(用户名是否存在、密码不显示、3次密码错误退出)
3)退出
b. 用户登录成功,进入二级菜单
import time
import random
class User():
UserList = [] #用户信息列表
Guanlist = [] #管理员信息列表
ShopList = [[{'商品':'杯子'},{'价格':'20'}],[{'商品':'牙刷'},{'价格':'10'}],[{'商品': '牙膏'}, {'价格': '15'}],[{'商品':'洗面奶'},{'价格':'40'}]]
DDxinxi = [] #订单信息列表
count = 0
def __init__(self):
self.__userName=None
self.__userPwd =None
self.__querenPwd = None
self.__czMiMa = None #充值密码
self.__shenFen =None
self.__zijin=0 #新用户默认资金
self.__phoneNum=None #用户电话
self.__area=None #用户地址
self.__xinXi = {"资金":self.__zijin,"电话":self.__phoneNum,"地址":self.__area}
self.__shopM = None #用户输入的购买商品的名称
self.__price =0 #对应商品的价格
def oneInterFace(self): #菜单首页
print("欢迎来勇哥购物系统")
print("="*30)
print("1.用户注册")
print("2.用户登陆")
print("3.退出")
while True:
x = int(input("请选择输入 1、2、3:"))
if x == 1:
self.zhuce()
break
elif x ==2:
self.login()
break
elif x ==3:
print("已退出")
break
else:
print("输入有误,请重新输入")
continue
break
def zhuce(self): #新用户注册界面
print("~"*30)
print("欢迎来到注册界面:")
while True:
self.__userName = input("请输入用户名:")
if self.__userName =="":
print("用户名不能为空,请重新输入")
continue
if self.__userName in User.UserList:
print("用户名重复,请重新输入!")
continue
else:
pass
self.__userPwd = input("请输入密码:") #后期要改
if self.__userPwd == "":
print("密码不能为空,请重新输入")
continue
self.__querenPwd = input("请再次输入确认密码:")
self.__czMiMa = input("请输入充值密码:")
self.__phoneNum = input("请输入电话号码:")
self.__area = input("请输入详细住址:")
if self.__userPwd != self.__querenPwd:
print("确认密码有误,请重新输入!")
continue
else:
userxinxi={"用户名":self.__userName,"密码":self.__querenPwd,"充值密码":self.__czMiMa,
"资金":self.__zijin,"电话号码":self.__phoneNum,"地址":self.__area}
User.UserList.append(userxinxi)
print("注册成功,快去登录吧!")
print("~"*30)
print(User.UserList)
self.oneInterFace()
break
break
def login(self): #用户登录界面
self.__loginName = None
self.__loginPwd = None
print("-"*30)
print("欢迎来到登陆界面")
if len(User.UserList) == 0: #由于用户列表里没有元素时,后续执行会导致系统运行中断,所以提前判断,以防万一。
print("注册后才能登陆,自动为您跳转注册界面,请稍候……")
time.sleep(2)
self.zhuce()
while User.count<3:
self.__loginName = input("请输入用户名:")
for userxinxi in User.UserList:
if self.__loginName != userxinxi['用户名']:
User.count += 1
print("抱歉,用户名不存在,请重新输入!")
self.login()
break
break
if User.count ==3: #如果用户名错误高达三次,没有必要再输出密码
break
self.__loginPwd = input("请输入登录密码:")
for userxinxi in User.UserList:
if self.__loginName == userxinxi['用户名']:
if self.__loginPwd !=userxinxi['密码']:
print("密码错误,请重新输入")
User.count += 1
self.login()
break
else:
print("登陆成功!")
print("-" * 30)
self.twoInterface()
break
break
break
break
else:
print("用户名或密码错误已达到3次,系统自动退出")
def twoInterface(self): #登录后的第二界面
print("*"*30)
print("勇哥购物商城欢迎您!!!")
print("=" * 30)
print("1.用户存款")
print("2.修改密码")
print("3.购买商品")
print("4.商品搜索")
print("5.商品排行")
print("6.订单操作")
print("7.商品操作")
print("8.退出操作")
print("="*30)
while True:
m = int(input("请选择以上功能,请键入(1、2、3、4、5、6、7、8)>>"))
if m==1:
self.cunKuan()
break
elif m==2:
self.xiuGaiPwd()
break
elif m==3:
self.gmShop()
break
elif m==4:
self.shopSS()
break
elif m==5:
self.xLpaiH()
break
elif m==6:
self.ddCaoz()
break
elif m==7:
self.shopCz()
break
elif m==8:
self.oneInterFace()
break
else:
print("输入有误,请重新输入。")
continue
break
def cunKuan(self): #用户充值界面
self.__moneyPwd = None
self.__moneyNum = None
print("#"*30)
while True:
self.__moneyPwd = input("请输入你的充值密码")
for userxinxi in User.UserList:
if self.__moneyPwd == userxinxi['充值密码']:
self.__moneyNum = int(input("请输入充值金额:"))
if self.__moneyNum <= 0:
print("请您正确输入!")
self.cunKuan()
else:
self.__zijin += self.__moneyNum
print("资金充值完成,现有金额:",self.__zijin)
self.twoInterface()
break
else:
print("密码错误!")
self.cunKuan()
break
pass
def xiuGaiPwd(self): #修改密码界面
self.__newPwd = None
while True:
oldPwd = input("请输入原来密码:")
for userxinxi in User.UserList:
if oldPwd == userxinxi["密码"]:
self.__newPwd = input("请输入新密码")
self.__userPwd = self.__newPwd
print("密码修改成功,请重新登陆")
self.login()
break
else:
print("您输入的原密码错误!请核对后再试!")
continue
break
pass
def gmShop(self): #购买商品界面
result = [tp[0] + " " + tp[1] for tp in [[it[k] for it in shop for k in it] for shop in User.ShopList]]
for temp in result:
print(temp)
while True:
self.__shopM=input("请输入要购买的商品名:")
for lists in User.ShopList:
for listtemp in lists[0].values():
if self.__shopM == listtemp:
for self.__price in lists[1].values():
print(self.__shopM,"的价格为:",self.__price)
self.__zijin -= int(self.__price)
if self.__zijin>0:
print(self.__shopM,"购买成功!账户还剩余额:",self.__zijin)
print("自动生成订单中……")
time.sleep(2)
self.ddCaoz()
else:
print("余额不足,系统正在进行自动跳转充值界面!请稍候……")
time.sleep(2)
self.cunKuan()
break
else:
print("商品不存在,请重新输入")
self.gmShop()
continue
break
break
break
def shopSS(self):
print("^"*30)
print("欢迎来到商品搜索界面")
shopname = input("请输入要搜索的商品名称:")
if shopname in [tp[0] for tp in [[it[k] for it in shop for k in it] for shop in User.ShopList]]:
self.gmShop() #商品存在,跳到购买商品界面
else:
print("抱歉,该商品信息不存在!!!")
self.shopSS()
pass
def xLpaiH(self): #从京东爬取,按照价格由高到低排行
print("="*30)
print("本数据实时来源于京东:")
print("-"*30)
print("--------各大品牌手机按价格由高到低排行-----------")
import spinph ####注意:导入的spinph.py在文章下方
print("="*30)
yhsr = input("退出请键入任意键后回车:")
if yhsr != " ":
print("请稍候,正在为您跳转……")
time.sleep(1)
self.twoInterface()
else:
pass
pass
def ddCaoz(self): #生成订单界面
print("*"*30)
print("以自动为您生成订单,详细信息如下:")
print("-"*30)
a = (random.randint(0, 10) for _ in range(18))
print("订单编号:")
ddbh = []
for i in a:
print(i,end="")
ddbh.append(i)
print()
print("下单时间:",time.ctime())
print("商品名称:",self.__shopM)
print("商品价格:",self.__price)
print("商品数量:",1)
print("用户名 :",self.__userName)
print("电话 :",self.__phoneNum)
print("邮寄地址:",self.__area)
print("-"*30)
ddxx = {'订单编号':ddbh,'下单时间':time.ctime(),'商品名称':self.__shopM,'商品价格':self.__price,
'商品数量':1,'用户名':self.__userName,'电话':self.__phoneNum,'邮寄地址':self.__area}
User.DDxinxi.append(ddxx) #将订单信息存储到列表中
# print(User.DDxinxi)
pd = input("是否继续购物y/n(继续请键入y,退出请键入n或任意键):")
if pd == 'y':
print("三秒钟后,自动跳回购买界面,请稍候……")
print("*"*30)
time.sleep(3)
self.gmShop()
elif pd !='y':
print("*" * 30)
print("已退出购买界面")
self.twoInterface()
else:
pass
pass
def shopCz(self):
print("注意!只有管理员才有权限进行商品操作!")
self.__shenFen = input("您是否想成为本购物系统的管理员呢?(y/n)")
if self.__shenFen =="y":
glxinxi = {"用户名":self.__userName,"密码":self.__querenPwd,"资金":self.__zijin,
"电话号码":self.__phoneNum,"地址":self.__area}
User.Guanlist.append(glxinxi)
print("----注意!你的信息已自动录入管理员的信息列表,请合理操作!!!----")
print("-----------------恭喜您已经成为管理员!!!-----------------------")
else:
time.sleep(2)
print("正在跳出界面,请稍候……")
self.twoInterface()
glogin = input("请输入管理员姓名:")
glpwd = input("请输入管理员密码:")
for glxinxis in User.Guanlist:
if glogin == glxinxis["用户名"] and glpwd == glxinxis["密码"]:
print("成功登陆管理员界面!!!")
break
else:
print("输入有误,2秒后自动退出")
time.sleep(2)
self.twoInterface()
while True:
print("1.添加商品 | 2.删除商品 | 3.修改商品 | 4.查看商品 | 5.退出")
glsr = int(input("请选择(1、2、3、4):"))
if glsr == 1:
tjspm = input("请输入想添加的商品名称:")
tjspj = input("请输入所添加商品的价格:")
tjxx = {"商品":tjspm}
tjxxj = {"价格":tjspj}
listq = [tjxx,tjxxj]
User.ShopList.append(listq)
print("添加商品信息成功!")
print(User.ShopList)
xx = input("是否继续添加y/n:")
if xx != "y":
break
else:
pass
elif glsr ==2:
delm = input("请输入想要删除的商品名:")
for lists in User.ShopList:
for listtemp in lists[0].values():
if delm == listtemp:
del lists[0]
else:
print("商品不存在,请重新输入……")
for listsx in User.ShopList:
if len(listsx) != 2:
User.ShopList.remove(listsx)
print(User.ShopList)
else:
break
elif glsr == 3:
xg = input("请输入要修改的商品名:")
for lists in User.ShopList:
for listtemp in lists[0].values():
if xg == listtemp:
jtxg = input("请修改商品名:")
jtxg1 = input("请修改商品价格:")
listxxg = []
xgzd = {'商品':jtxg}
xgjzd = {'价格':jtxg1}
listxxg=[xgzd,xgjzd]
User.ShopList.append(listxxg)
delm = xg
for lists in User.ShopList:
for listtemp in lists[0].values():
if delm == listtemp:
del lists[0]
for listsx in User.ShopList:
if len(listsx) != 2:
User.ShopList.remove(listsx)
print(User.ShopList)
break
else:
print("该商品不存在")
break
break
elif glsr == 4:
result = [tp[0] + " " + tp[1] for tp in [[it[k] for it in shop for k in it] for shop in User.ShopList]]
for temp in result:
print(temp)
elif glsr == 5:
self.twoInterface()
break
else:
print("输入有误,请重新输入!")
continue
break
users=User()
users.oneInterFace()
如下是导入的spinph.py的爬虫代码(数据采集):
import urllib.request
import time
from lxml import etree #处理数据用的 xpath 功能
page = 5
s = 121
newresult=[] #初步优化的结果 #以下 代码 的 注释部分 为 测试部分
phonePrice=[] #手机价格
newresults=[] #优化后的结果
url = "https://search.jd.com/Search?keyword=%E4%BA%AC%E4%B8%9C%E6%89%8B%E6%9C%BA%E9%94%80" \
"%E9%87%8F%E6%8E%92%E8%A1%8C%E6%A6%9C&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&suggest=8.def.0." \
"V14--12s0%2C20s0%2C38s0&wq=%E6%89%8B%E6%9C%BA%E9%94%80%E9%87%8F%E6%8E%92%E8%A1%8C&psor" \
"t=1&page={0}&s={1}&click=0.format(page,s)".format(page,s) #由于优化条件有限,暂未分页爬取
headers={
"Request URL": "https://search.jd.com/im.php?r=438806543&t=1566029647.6762&cs=44d88edca41a9cfd4279867d5173a1dd",
"user-agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3719.400 QQBrowser/10.5.3715.400"
}
resp = urllib.request.Request(url,headers=headers)
response = urllib.request.urlopen(resp)
if response.getcode() == 200:
with open("index.html","w",encoding="utf-8") as fp:
fp.write(response.read().decode("UTF-8"))
html = etree.parse('index.html',etree.HTMLParser())
result = html.xpath('//a/em//text()')
jgresult = html.xpath('//strong/i//text()')
# print("原始数据:")
# print(result)
# print(jgresult)
# print()
for telephoneName in result:
#筛选(删除重复遍历(具体情况需要具体分析))
if len(telephoneName)<4 or telephoneName[0] == " " or telephoneName == "京品手机" or telephoneName[0] == "【" \
or telephoneName[0] == "(" or telephoneName[0] == "(" or telephoneName[0]=="2" or telephoneName[0]=="白":
del telephoneName
else:
# print(telephoneName)
newresult.append(telephoneName)
# print()
# print(len(newresult))
# print(len(jgresult))
for telephonePrice in jgresult:
# print(telephonePrice)
phonePrice.append(telephonePrice) #其实jgresult就是列表,但为了更清晰的表达,所以遍历后,重新加入新的列表phonePrice中。
for temp in newresult:
if temp[-1] == "戏":
temps=temp+"手机"
newresults.append(temps)
else:
newresults.append(temp)
# print("优化后的数据:")
# print(newresults)
# print(phonePrice)
# print()
dictionary = dict(zip(newresults,phonePrice)) #dict(zip(列表1,列表2))将两个列表封装成字典,前者为key,后者为value
# print("封装成字典:")
# print(dictionary)
for key,value in dictionary.items():
print(key," : ¥",value)
如上问题中,涉猎比较广泛,如有纰漏,请多包涵