分别点击 “Save” 保存这两个文件,会保存在与 ui.tcl 的同一目录。
“python GUI” 是界面逻辑,保存后的文件名为 ui.py,不需要动。
“Support Module” 是触发事件代码,我们相应的逻辑就是在这里面添加:
打开 ui_support.py
,找到设置的 “command”,即为函数名:
clean 函数为点击【清除】按钮后,把文本框清除:
creat_menu 函数为点击【生成菜谱】按钮后的逻辑,从 csv 中随机抽取三菜一汤显示在文本框,显示词云在标签栏。
其主要为:读取 csv,DataFrame 转化为 list,合并【三菜一汤】,制作菜单的文本,保存食材词,菜单文本框插入,词云生成,插入词云:
这样所有逻辑都完成了,运行 ui_support.py
即可开始菜谱生成啦~
spider.py
import requests
import csv
from lxml import etree
from fake_useragent import UserAgent
def create_csv():
‘’’
创建 foods.csv, soups.csv
‘’’
head = [‘name’,‘food’,‘score’,‘link’]
csvs = [‘foods.csv’,‘soups.csv’]
for c in csvs:
with open(c,‘w’,encoding=‘gbk’,newline=‘’) as f:
writer = csv.writer(f)
writer.writerow(head)
def get_html(url,kind):
‘’’
请求 html
‘’’
headers = {
‘User-Agent’ : UserAgent().random,
‘Cookie’ : ‘bid=SUKKdKjF; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%22171a785835191-0292964d820ab7-4313f6a-921600-171a78583520%22%2C%22%24device_id%22%3A%22171a785835191-0292964d820ab7-4313f6a-921600-171a78583520%22%2C%22props%22%3A%7B%22%24latest_referrer%22%3A%22%22%2C%22%24latest_referrer_host%22%3A%22%22%2C%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%7D%7D; __utmz=177678124.1587653477.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __gads=ID=e0150cd671284025:T=1587653477:S=ALNI_Mbm6h5yX4RCMFDKDV9SBCRwZXLwFg; Hm_lvt_ecd4feb5c351cc02583045a5813b5142=1587653477,1587700573; __utma=177678124.702716191.1587653477.1587653477.1587700573.2; __utmc=177678124; __utmb=177678124.44.10.1587700573; Hm_lpvt_ecd4feb5c351cc02583045a5813b5142=1587703641’,
‘Host’ : ‘www.xiachufang.com’,
‘Referer’ : kind.split(‘?’)[0]
}
response = requests.get(url,headers=headers)
if response.status_code == 200:
return response
else:
return
def get_infos(response):
‘’’
提取数据
‘’’
infos = []
html = etree.HTML(response.text)
menus = html.xpath(‘//ul[@class=“list”]/li’)[:20]
for menu in menus:
name = menu.xpath(‘./div/div/p[1]/a/text()’)[0].replace(‘\n’,‘’).replace(’ ‘,’')
food = menu.xpath(‘./div/div/p[@class=“ing ellipsis”]’)[0]
food = food.xpath(‘string(.)’).replace(‘\n’,‘’).replace(’ ‘,’')
score = menu.xpath(‘./div/div/p[3]/span[1]/text()’)[0]
link = menu.xpath(‘./div/div/p[1]/a/@href’)[0]
link = ‘http://www.xiachufang.com’ + link
infos.append([name,food,score,link])
return infos
def write_to_csv(infos,file):
‘’’
写入 csv
‘’’
with open(file,‘a+’,encoding=‘utf8’,newline=‘’) as f:
writer = csv.writer(f)
for info in infos:
writer.writerow(info)
if name == ‘main’:
count = 1
create_csv()
kind_urls = [‘http://www.xiachufang.com/category/40076/’,
‘http://www.xiachufang.com/category/40077/’,
‘http://www.xiachufang.com/category/40078/’,
‘http://www.xiachufang.com/category/20130/’]
for kind in kind_urls:
kind += ‘?page={}’
urls = [kind.format(str(i)) for i in range(1,12)]
for url in urls:
response = get_html(url,kind)
if response == None:
continue
infos = get_infos(response)
判断是否为【汤羹】url,写入对应的 csv
if ‘20130’ not in url:
file = ‘foods.csv’
else:
file = ‘soups.csv’
write_to_csv(infos,file)
print(‘已爬取 %d 页菜谱’ % count)
count += 1
ui_support.py
#! /usr/bin/env python
-- coding: utf-8 --
Support module generated by PAGE version 5.1
in conjunction with Tcl version 8.6
Apr 24, 2020 07:03:52 PM CST platform: Windows NT
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
def init(top, gui, *args, **kwargs):
global w, top_level, root
w = gui
top_level = top
root = top
def clean():
‘’’
此处为点击【清除】按钮后的逻辑
点击清除文本框以及词云
‘’’
w.Text1.delete(‘1.0’, ‘end’)
sys.stdout.flush()
def creat_menu():
‘’’
此处为点击【生成菜谱】按钮后的逻辑
从 csv 中随机抽取三菜一汤
显示在文本框
显示词云在标签栏
‘’’
import pandas as pd
import numpy as np
import wordcloud
menu_df = pd.read_csv(‘foods.csv’, encoding=‘utf8’)
soup_df = pd.read_csv(‘soups.csv’, encoding=‘utf8’)
DataFrame 转化为 list
menus = menu_df.sample(3)
menus = np.array(menus)
menus = menus.tolist()
soup = soup_df.sample()
soup = np.array(soup)
soup = soup.tolist()
合并【三菜一汤】
文末有福利领取哦~
👉一、Python所有方向的学习路线
Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。
👉二、Python必备开发工具
👉三、Python视频合集
观看零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。
👉 四、实战案例
光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。(文末领读者福利)
👉五、Python练习题
检查学习结果。
👉六、面试资料
我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。
👉因篇幅有限,仅展示部分资料,这份完整版的Python全套学习资料已经上传
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!