python爬取天气

lin00362

发布日期: 2021-06-04 19:28:36 浏览量: 92
评分:
star star star star star star star star star star_border
*转载请注明来自write-bug.com

python 爬虫

简单的爬取天气情况

  1. from pypinyin import lazy_pinyin
  2. import requests
  3. from lxml import etree
  4. import re
  5. Baseurl = 'https://www.tianqi.com/'
  6. headers = {
  7. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36',
  8. }
  9. while True:
  10. citry = input("请输入城市名称:")
  11. pin_list = lazy_pinyin(citry, style=False)
  12. citry_pin = ''.join(pin_list)
  13. Url = Baseurl + citry_pin
  14. request = requests.get(url=Url,headers=headers)
  15. request.encoding = ''
  16. Data = etree.HTML(request)
  17. print(Data.xpath('//div//dl//dd[@class="name"]/h2/text()'))
  18. Tianqi_Data = etree.HTML(request)
  19. citry_name = Tianqi_Data.xpath('//div//dl//dd[@class="name"]/h2/text()')[0]
  20. citry_week = Tianqi_Data.xpath('//div//dl//dd[@class="week"]/text()')[0]
  21. citrys = f'{citry_name}\n{citry_week}\n'
  22. citry_weather_now1 = Tianqi_Data.xpath('//div//dl//dd//p[@class="now"]/b/text()')[0]
  23. citry_weather_now3 = Tianqi_Data.xpath('//div//dl//dd[@class="weather"]/span/b/text()')[0]
  24. citry_weather_now4 = Tianqi_Data.xpath('//div//dl//dd[@class="weather"]/span/text()')[0]
  25. citry_weather = f'{citry_weather_now1}℃\n天气:{citry_weather_now3}\n{citry_weather_now4}\n'
  26. citry_shidus = Tianqi_Data.xpath('//div//dl//dd[@class="shidu"]/b/text()')
  27. citry_shidu = ",".join(citry_shidus)
  28. citry_kongqi1 = Tianqi_Data.xpath('//div//dl//dd[@class="kongqi"]/h5/text()')[0]
  29. citry_kongqi2 = Tianqi_Data.xpath('//div//dl//dd[@class="kongqi"]/span/text()')
  30. citry_kongqi3 = Tianqi_Data.xpath('//div//dl//dd[@class="kongqi"]/h6/text()')[0]
  31. citry_kongqi = f'{citry_kongqi1}\nPM2.5:{citry_kongqi3.split(":")[-1]}\n{citry_kongqi2[0]}\n{citry_kongqi2[1]}\n'
  32. print(f'{citrys}\n{citry_weather}\n{citry_shidu}\n\n{citry_kongqi}')
  33. YN = input('是否查询未来天气(Y/N):')
  34. if YN == 'Y':
  35. day = input('请输入查询未来天气天数(3/7/15/30/40):')
  36. url_Jinqi = f'{Url}/{day}'
  37. req = requests.get(url=url_Jinqi, headers=headers).text
  38. Data_jinqi = etree.HTML(req)
  39. Q_time = Data_jinqi.xpath('//ul[@class="weaul"]//li//div//span/text()')
  40. Q_weather = Data_jinqi.xpath('//div[@class="weaul_z"]//text()')
  41. j = 0
  42. result = []
  43. for i in range(0, len(Q_time), 4):
  44. weather = [Q_weather[i] for i in range(0, len(Q_weather), 5)]
  45. result.append(
  46. Q_time[i] + ',' + Q_time[i + 1] + ',' + weather[j] + ',' + '温度:' + Q_time[i + 2] + '~' + Q_time[
  47. i + 3] + '℃')
  48. j += 1
  49. for item in result:
  50. print(item)
  51. else:
  52. print('已退出!')
上传的附件 cloud_download 天气.py ( 3.05kb, 5次下载 )

发送私信

4
文章数
1
评论数
最近文章
eject