如何用Python爬取每天天气
时间: 2023-05-25 19:04:03 浏览: 80
要爬取每天的天气,需要先找到一个提供天气数据的网站并确定数据的获取方式。一般来说,可以通过网站的API或者直接爬取网页内容来获取天气数据。
以下是一个使用Python爬取天气数据的例子:
1. 导入需要用到的库
```python
import requests
from bs4 import BeautifulSoup
```
2. 设定要爬取的城市和日期
```python
city = "北京"
date = "2021-10-26"
```
3. 发送请求,获取网页内容
```python
url = f"https://tianqi.moji.com/weather/china/{city}/{date}"
response = requests.get(url)
```
4. 解析网页内容,获取天气数据
```python
soup = BeautifulSoup(response.text, "html.parser")
temperature = soup.find("div", attrs={"class": "wea_info"}).find("em").text.strip()
weather = soup.find("div", attrs={"class": "wea_info"}).find("b").text.strip()
wind = soup.find("div", attrs={"class": "wea_info"}).find("span").get("title")
```
在上面的代码中,我们使用了BeautifulSoup库来解析网页内容,并从中获取了当天的温度、天气和风力数据。
5. 将数据存储到文件或数据库中
```python
with open("weather.txt", "a", encoding="utf-8") as f:
f.write(f"{date} {city} {temperature} {weather} {wind}\n")
```
最后,我们将获取到的数据存储到文本文件中,或者将其保存到数据库中,以便后续分析和使用。
注意:对于某些网站,需要在请求头中添加一些额外的信息才能成功获取数据。在实际使用中,需要根据具体情况做出相应调整。