[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
返回列表 发帖

[技术讨论] [学习笔记]Python爬取天气信息(我的第一个爬虫)

本帖最后由 Gin_Q 于 2020-7-28 16:36 编辑
  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.                 'lastCountyId=58362; lastCountyPinyin=shanghai; lastCountyTime=1595925050',
  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))
复制代码

很有意思,但不够完美唉
也许可以试试跟据网页内部的API来爬取?
最近也在搞爬虫,一起加油(ง •̀_•́)ง

TOP

回复 2# wujunkai


    感觉爬虫就是拿到数据,提取需要的!难的是怎么拿到数据!

TOP

回复 1# Gin_Q

怎么是爬到东莞的天气,如何爬取上海的天气?

TOP

回复 4# netdzb


    需要去网站查询
   'lastCountyId=58362; lastCountyPinyin=shanghai; lastCountyTime=1595925050' 加到 city_list

TOP

返回列表