鱼C论坛

 找回密码
 立即注册
查看: 1472|回复: 2

[技术交流] 爬取天气信息(我的第一个爬虫)增加简单的tkinter

[复制链接]
发表于 2020-6-8 18:48:11 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 Cool_Breeze 于 2020-7-27 11:21 编辑

tkinter
  1. #coding=utf-8

  2. import tkinter as tk
  3. import time
  4. from tianqi import main
  5. def home_mian():
  6.     font = 'Consolas', 11
  7.     home = tk.Tk()
  8.     home.title('天气查询 by cool_breeze')
  9.     home.geometry('800x600')
  10.    
  11.     var = tk.StringVar()
  12.     varL = []
  13.     for n in range(1,18):
  14.         varL.append(tk.StringVar()) #将对象放入列表

  15.     Llist = []
  16.     for n in range(1,18):
  17.         Llist.append(tk.Label(home, textvariable=varL[n-1], bg ='honeydew', font=font))
  18.     L0 = tk.Label(home, textvariable=var, bg ='honeydew', font=font)

  19.     for n in Llist:
  20.         n.pack(fill=tk.X, side=tk.TOP)
  21.     L0.pack(fill=tk.X, side=tk.TOP)

  22.     def tishi():
  23.         var.set('正在获取网页信息...')
  24.         home.update() #更新窗口
  25.     def zigong(n):
  26.         tishi()
  27.         res = main(n)
  28.         for i,j in enumerate(varL):
  29.             j.set(res[i])
  30.         var.set('')
  31.         
  32.     def exit_():
  33.         exit()
  34.    
  35.     zg_bt = tk.Button(home,text='自流井',font=font,bg = 'ivory',width=10,height=1,command=lambda:zigong(1)).pack(side='left')
  36.     cd_bt = tk.Button(home,text='成都',font=font,bg = 'ivory',width=10,height=1,command=lambda:zigong(2)).pack(side='left')
  37.     dg_bt = tk.Button(home,text='东莞',font=font,bg = 'ivory',width=10,height=1,command=lambda:zigong(3)).pack(side='left')
  38.     ex_bt = tk.Button(home,text='退出',font=font,bg = 'ivory',width=10,height=1,command=exit_).pack(side='left')

  39.     home.mainloop()
  40. if __name__ == '__main__':
  41.     home_mian()
复制代码

爬虫
  1. #coding=utf-8

  2. import urllib.request,urllib.error
  3. from bs4 import BeautifulSoup as bfs
  4. import os
  5. import re

  6. def main(number):
  7.     city_list = [
  8.                 'positionCityID=59289; positionCityPinyin=zigong; lastCountyId=71992; lastCountyPinyin=ziliujing',
  9.                 'lastCountyId=56294; lastCountyPinyin=chengdu; lastCountyTime=1591617161',
  10.                 'lastCountyId=59289; lastCountyPinyin=dongguan; lastCountyTime=1591612281',
  11.                 ]
  12.    
  13.     url = 'http://tianqi.2345.com/'
  14.    
  15.     html = askurl(url, city_list[number-1])
  16.     data = getdata(html)
  17.     return data

  18. def format(string):
  19.     str_len = len(string)
  20.     max_len = 13
  21.     if str_len >= 1 and str_len <= max_len:
  22.         return string.center(max_len - str_len)
  23.     else:
  24.         return string

  25. def askurl(url,cookkey):
  26.     head = {
  27.     'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
  28.     'Accept-Language': 'zh-CN,zh;q=0.9',
  29.     'Cookie': 'qd_dz_ct=59289; sts=1; theme=-1; wc=59289; lc=59289; lc2=59289; wc_n=%25u4E1C%25u839E; ' + cookkey,
  30.     '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.3641.400 QQBrowser/10.4.3284.400'
  31.     }
  32.    
  33.     req = urllib.request.Request(url=url, headers=head)
  34.     try:
  35.         response = urllib.request.urlopen(req)
  36.         if response.chunked:
  37.             print('访问:{} 失败!\n请检查网络是否可以正确的访问Internet!'.format(url))
  38.             exit()
  39.     except urllib.error.URLError as err:
  40.         print('\n网络连接失败!\n请检查网络连接!', err)
  41.         input('按任意键退出!')
  42.         exit()
  43.     html = bfs(response,'html.parser') #解析html
  44.     # print(html)
  45.    
  46.     return html
  47. def getdata(html):
  48.     datalist = []
  49.     datalist.append(html.find('em', class_="location-city location-font1").string)
  50.     date_temp = html.find('p', class_="date").contents
  51.     datalist.append(date_temp[0].string + ' ' + date_temp[2].string)
  52.     datalist.append(date_temp[1].string)
  53.     datalist.append(date_temp[3].string)
  54.     #天气情况
  55.     weather = html.find('a', class_="wea-info-index")
  56.     datalist.append(weather.span.string + weather.b.string)
  57.     datalist.append(html.find('a', class_="wea-other-a-we").string)
  58.     datalist.append('空气质量:' + html.find('a', class_="wea-aqi-tip-index").em.string)
  59.     weather = html.find('ul', class_="wea-info-tip").find_all('li')
  60.     datalist.append(weather[0].span.string + ' : ' + weather[0].em.string)
  61.     datalist.append(weather[1].span.string + ' : ' + weather[1].em.string)
  62.     datalist.append(weather[2].span.string + ' : ' + weather[2].em.string)
  63.     # print(datalist)
  64.    
  65.     #获取未来六天的天气数据
  66.     tomorrow = [[],[],[],[],[],[]]
  67.    
  68.     def get_tomorrw(htmlobj, index): #相应数据
  69.         temp = htmlobj.contents
  70.         tomorrow[index].append(format(temp[1].text + ' ' + temp[3].text))
  71.         tomorrow[index].append(format(temp[7].text))
  72.         tomorrow[index].append(format(temp[9].text + ' ' + temp[11].text))
  73.         tomorrow[index].append(format('空气质量:' + temp[13].text))

  74.     info_tomorrow = html.find('ul', class_="weaday7 wea-white-icon")
  75.     a_list = info_tomorrow.find_all('a')
  76.     for day, index in zip(range(2,14,2),range(6)):
  77.         get_tomorrw(a_list[day], index)
  78.         
  79.     #温度
  80.     script = html.findAll('script')[-1]
  81.     H = re.compile('var day7DataHight = \[(.*)\]')
  82.     L = re.compile('var day7DataLow = \[(.*)\]')
  83.     H_list = re.findall(H,str(script))[0].split(',')
  84.     L_list = re.findall(L,str(script))[0].split(',')
  85.     n = 0
  86.     for i,j in zip(L_list, H_list):
  87.         if not n:
  88.             n+=1;continue
  89.         tomorrow[n-1].insert(3, format(i + ' ~ ' + j))
  90.         n+=1
  91.     # print(datalist + tomorrow)   
  92.     return datalist + tomorrow
  93. if __name__ == '__main__':
  94.     print(main(3))
复制代码



desktop 2020-06-20 22-23-53.gif
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-6-9 00:09:25 | 显示全部楼层
能改变城市吗?没有我所在的城市啊
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-6-9 00:43:44 | 显示全部楼层
本帖最后由 Cool_Breeze 于 2020-6-9 09:49 编辑
myhic 发表于 2020-6-9 00:09
能改变城市吗?没有我所在的城市啊


可以自己添加城市的,将Cookie添加到列表就好了!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-21 14:03

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表