python爬虫爬取天津天气数据
时间: 2023-10-06 22:08:58 浏览: 96
您可以使用Python编写爬虫来获取天津的天气数据。以下是一个示例代码:
```python
import requests
from bs4 import BeautifulSoup
def get_tianjin_weather():
url = "http://www.weather.com.cn/weather/101030100.shtml"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36"
}
response = requests.get(url, headers=headers)
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'html.parser')
# 获取天气信息
weather_info = soup.find('ul', class_='t').find_all('li')
# 提取数据
temperature = weather_info[0].find('span').get_text()
weather = weather_info[1].get_text()
wind = weather_info[2].get_text()
return temperature, weather, wind
# 调用函数获取天津的天气数据
temperature, weather, wind = get_tianjin_weather()
print("天津天气:")
print("温度:", temperature)
print("天气:", weather)
print("风力:", wind)
```
请确保在运行代码之前安装了`requests`和`beautifulsoup4`库。这个示例代码会请求天津天气网站(http://www.weather.com.cn/weather/101030100.shtml),然后使用BeautifulSoup库解析网页内容,提取所需的天气数据并打印输出。
阅读全文