|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
根据前辈们爬天气的代码加上GUI页面,目前有个问题就是运行一次只能查询一次,再次查询需要重新运行,有没有大佬帮忙优化一下
import tkinter
import requests
import pypinyin
from bs4 import BeautifulSoup
from tkinter import messagebox
def inp():
city = ''
chengshi = en1.get()
chengshi =chengshi.strip()
if chengshi == '':
messagebox.showinfo("温馨提示", "城市不能为空")
else:
for each in chengshi:
city = city + pypinyin.pinyin(each, style=pypinyin.NORMAL)[0][0]
return city,chengshi
def get(city, cityname_zh):
url = "https://www.tianqi.com/"+ city +"/"
headers = {
'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36'
}
res = requests.get(url, headers=headers).text
soup = BeautifulSoup(res, 'html.parser')
du = soup.find("p", class_="now")
shidu_atart = soup.find("dd", class_="shidu")
tianqi = soup.find("dd", class_="weather")
shidu = shidu_atart.find_all("b")
text = str(cityname_zh+"市天气预报\n---------------------"+"\n天气:"+tianqi.span.b.text+"\n"+"温度:"+du.b.text+"摄氏度"+"\n"+shidu[0].text+"\n"+shidu[1].text+"\n"+shidu[2].text)
la2 = tkinter.Label(root, width=200, height=300, background="#FFFFFF", borderwidth=2, text=text)
la2.pack()
def run():
c, y = inp()
get(city=c, cityname_zh=y)
root = tkinter.Tk()
root.geometry("400x500")
root.title("天气查询")
la1 = tkinter.Label(root, text="请输入城市")
la1.pack()
en1 = tkinter.Entry(root)
en1.pack()
ba = tkinter.Button(root, text="查询", command=run)
ba.pack()
root.mainloop() |
|