网页数据爬取天气网站
时间: 2023-12-22 22:26:33 浏览: 27
以下是爬取天气网站数据的基本思路和步骤:
1. 查看和分析天气网网页规律,确定需要爬取的数据类型和网页链接。
2. 使用Python的requests库向网页发送请求,获取网页源代码。
3. 使用BeautifulSoup库解析网页源代码,提取需要的数据。
4. 将提取的数据保存到本地文件或数据库中。
下面是一个简单的示例代码,用于爬取天气网站的当天24小时天气信息:
```python
import requests
import json
# 发送请求,获取网页源代码
url = 'http://www.weather.com.cn/weather/101010100.shtml'
response = requests.get(url)
html = response.content.decode('utf-8')
# 解析网页源代码,提取当天24小时天气信息
soup = BeautifulSoup(html, 'html.parser')
script = soup.find('script', attrs={'type': 'text/javascript'})
json_str = script.string.split('hour3data=')[-1].split(';')[0]
data = json.loads(json_str)
# 输出当天24小时天气信息
for item in data:
print(item['jf'], item['jb'], item['jb2'], item['t'], item['rh'], item['wd'], item['ws'])
# 将当天24小时天气信息保存到本地文件
with open('weather.txt', 'w', encoding='utf-8') as f:
for item in data:
f.write(str(item) + '\n')
```