Python脚本制作天气查询实例代码

获取天气的主要代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

# cityCode 替换为具体某一个城市的对应编号

# 1、发送请求,获取数据

url = f'http://wthrcdn.etouch.cn/weather_mini?citykey={cityCode}'

res = requests.get(url)

res.encoding = 'utf-8'

res_json = res.json()

  

# 2、数据格式化

data = res_json['data']

city = f"城市:{data['city']}\n" 

# 字符串格式化的一种方式 f"{}" 通过字典传递值

  

today = data['forecast'][0]

date = f"日期:{today['date']}\n"  # \n 换行

now = f"实时温度:{data['wendu']}度\n"

temperature = f"温度:{today['high']} {today['low']}\n"

fengxiang = f"风向:{today['fengxiang']}\n"

type = f"天气:{today['type']}\n"

tips = f"贴士:{data['ganmao']}\n"

  

result = city + date + now + temperature + fengxiang + type + tips

  

print(result)

1、使用Qt Designer绘制窗口,保存为ui文件

2、把ui文件转为py文件

(1)在生成的ui文件目录下,打开cmd

(2)输入以下命令(注意替换名称)

pyuic5 -o destination.py source.ui

3、信号与槽函数的连接

1

2

3

4

5

# 1、清空按钮与对应函数连接

clearBtn.clicked.connect(widget.clearResult)

  

# 2、查询按钮与对应函数连接

queryBtn.clicked.connect(widget.queryWeather)

4、调用主窗口类

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

import sys    

from PyQt5.QtWidgets import QApplication , QMainWindow

from WeatherWin import Ui_widget

import requests

import json

  

class MainWindow(QMainWindow ):

    def __init__(self, parent=None):   

        super(MainWindow, self).__init__(parent)

        self.ui = Ui_widget()

        self.ui.setupUi(self)

  

        # 通过文本框传入想要搜索的城市名称:天津

        cityName = self.ui.weatherComboBox.currentText()

  

        # 获取天气部分省略

  

        # 在文本框显示查询结果

        self.ui.resultText.setText(result)

  

    def clearResult(self):

        print('* clearResult  ')

        self.ui.resultText.clear() 

  

if __name__=="__main__"

    app = QApplication(sys.argv) 

    win = MainWindow() 

    win.show() 

    sys.exit(app.exec_())

代码扩展:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

from tkinter import *

import urllib.request

import gzip

import json

from tkinter import messagebox

root = Tk()

def main():

  # 输入窗口

  root.title('Python学习交流群:973783996') # 窗口标题

  Label(root, text='请输入城市').grid(row=0, column=0) # 设置标签并调整位置

  enter = Entry(root) # 输入框

  enter.grid(row=0, column=1, padx=20, pady=20) # 调整位置

  enter.delete(0, END) # 清空输入框

  enter.insert(0, 'Python学习交流群:973783996') # 设置默认文本

  # enter_text = enter.get()#获取输入框的内容

   running = 1

   def get_weather_data(): # 获取网站数据

    city_name = enter.get() # 获取输入框的内容

    url1 = 'http://wthrcdn.etouch.cn/weather_mini?city=' + urllib.parse.quote(city_name)

    url2 = 'http://wthrcdn.etouch.cn/weather_mini?citykey=101010100'

    # 网址1只需要输入城市名,网址2需要输入城市代码

    # print(url1)

    weather_data = urllib.request.urlopen(url1).read()

    # 读取网页数据

    weather_data = gzip.decompress(weather_data).decode('utf-8')

    # 解压网页数据

    weather_dict = json.loads(weather_data)

    # 将json数据转换为dict数据

    if weather_dict.get('desc') == 'invilad-citykey':

      print(messagebox.askokcancel("xing", "你输入的城市名有误,或者天气中心未收录你所在城市"))

    else:

      # print(messagebox.askokcancel('xing','bingguo'))

      show_data(weather_dict, city_name)  def show_data(weather_dict, city_name): # 显示数据

    forecast = weather_dict.get('data').get('forecast') # 获取数据块

    root1 = Tk() # 副窗口

    root1.geometry('650x280') # 修改窗口大小

    root1.title(city_name + '天气状况') # 副窗口标题

     # 设置日期列表

    for i in range(5): # 将每一天的数据放入列表中

      LANGS = [(forecast[i].get('date'), '日期'),

           (forecast[i].get('fengxiang'), '风向'),

           (str(forecast[i].get('fengji')), '风级'),

           (forecast[i].get('high'), '最高温'),

           (forecast[i].get('low'), '最低温'),

           (forecast[i].get('type'), '天气')]

      group = LabelFrame(root1, text='天气状况', padx=0, pady=0) # 框架

      group.pack(padx=11, pady=0, side=LEFT) # 放置框架

      for lang, value in LANGS: # 将数据放入框架中

        c = Label(group, text=value + ': ' + lang)

        c.pack(anchor=W)

    Label(root1, text='今日' + weather_dict.get('data').get('ganmao'),

       fg='green').place(x=40, y=20, height=40) # 温馨提示

    Label(root1, text="StarMan: 49star.com", fg="green", bg="yellow").place(x=10, y=255, width=125,                              height=20) # 作者网站

    Button(root1, text='确认并退出', width=10, command=root1.quit).place(x=500, y=230, width=80, height=40) # 退出按钮

    root1.mainloop()

  # 布置按键

  Button(root, text="确认", width=10, command=get_weather_data) \

    .grid(row=3, column=0, sticky=W, padx=10, pady=5)

  Button(root, text='退出', width=10, command=root.quit) \

    .grid(row=3, column=1, sticky=E, padx=10, pady=5)

  if running == 1:

    root.mainloop()

 if __name__ == '__main__':

  main()

  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 好的,我可以为你讲解一下使用 Python 爬取指定网站数据的基本流程。 首先,我们需要使用 Python 的第三方库 requests 来发起 HTTP 请求,并使用 lxml 或 BeautifulSoup 解析响应的 HTML 页面。 然后,你可以使用 XPath 或 CSS 选择器来定位到你想要提取的数据,并提取它。 接下来,你可以将提取的数据存储到本地文件或数据库中,或者将它用于其他用途。 下面是一个使用 requests 和 BeautifulSoup 爬取网站标题的示例代码: ``` import requests from bs4 import BeautifulSoup # 发起请求并获取响应 response = requests.get('https://www.example.com') html = response.text # 使用 BeautifulSoup 解析 HTML 页面 soup = BeautifulSoup(html, 'lxml') # 提取网站标题 title = soup.title.string print(title) ``` 希望这对你有帮助。 ### 回答2: 通过使用Python脚本进行网页爬取数据是一种非常常见且实用的技术。以下是一个使用Python脚本爬取指定网站页面数据的示例: 首先,我们需要安装Python的一个第三方库,称为"Requests"。这个库可以帮助我们发送HTTP请求,从而获取网站的HTML内容。可以通过运行以下命令进行安装: ``` pip install requests ``` 接下来,我们需要使用Python脚本导入"Requests"库,并指定要爬取的网址。我们还可以通过添加一些HTTP头部信息来伪装成浏览器发送请求。例如,我们可以添加"User-Agent"头部字段来模拟浏览器: ```python import requests url = "https://example.com" headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"} response = requests.get(url, headers=headers) ``` 现在,我们可以使用"response"对象来访问从网站获取的HTML内容。我们可以通过调用"response.text"来获取HTML文档的字符串形式,然后使用其他Python库(如"Beautiful Soup")来解析和提取所需的数据。例如,我们可以通过以下代码,将HTML文档的标题提取出来: ```python from bs4 import BeautifulSoup soup = BeautifulSoup(response.text, "html.parser") title = soup.title.string print(title) ``` 这只是一个简单示例,说明了如何使用Python脚本爬取指定网站页面的数据。实际上,我们可以根据网站的不同结构和数据提取需求,使用不同的解析库和技术来处理和提取数据。同时,为了遵守网站的规则和法律,我们还需要遵循爬虫道德和使用协议。 ### 回答3: 以爬取豆瓣电影排行榜Top250为例。 首先,需要安装Python的爬虫库requests和解析库BeautifulSoup。打开终端或命令行界面,执行以下命令进行安装: ``` pip install requests beautifulsoup4 ``` 接下来,在Python脚本中导入所需的库: ```python import requests from bs4 import BeautifulSoup ``` 然后,指定要爬取的网页URL,并使用requests库发送GET请求获取网页的HTML内容: ```python url = "https://movie.douban.com/top250" response = requests.get(url) ``` 接下来,使用BeautifulSoup库对获取到的HTML内容进行解析,并提取出需要的数据: ```python soup = BeautifulSoup(response.text, "html.parser") ``` 在豆瓣电影排行榜页面上,每个电影的信息都包含在一个class为"item"的div元素中。可以使用select方法根据CSS选择器提取出所有的电影信息: ```python movies = soup.select(".item") ``` 接下来,可以遍历movies列表,提取出每个电影的名称、评分、导演等信息: ```python for movie in movies: title = movie.select(".title")[0].text rating = movie.select(".rating_num")[0].text directors = movie.select(".bd .info span")[0].text print("电影名称:", title) print("评分:", rating) print("导演:", directors) print("--------------------") ``` 最后,在命令行中执行Python脚本,即可获取到豆瓣电影排行榜Top250的电影名称、评分和导演信息。 以上就是指定网站页面使用Python脚本爬取数据的一个实例。通过发送HTTP请求获取网页内容,再通过解析库提取需要的数据,可以实现对网页数据的爬取和分析。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值