python爬取辽宁省所有天气信息生成excel
时间: 2023-11-08 20:54:05 浏览: 89
python爬取天气数据
好的,我可以提供一些关于爬取天气信息并生成excel文件的Python代码,你可以参考一下:
```python
import requests
from lxml import etree
import csv
# 获取网页HTML
url = 'http://www.weather.com.cn/weather/101070101.shtml'
response = requests.get(url).text
selector = etree.HTML(response)
# 获取天气信息
info = selector.xpath('//ul[@class="t clearfix"]')
city = selector.xpath('//div[@class="crumbs fl"]/a[2]/text()')[0]
filename = city + ".csv"
# 写入csv文件
with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["日期", "白天天气", "夜晚天气", "最高气温", "最低气温", "风向", "风力"])
for i in info:
# 获取日期、白天天气、夜晚天气、最高气温、最低气温、风向、风力数据
day = i.xpath('li/h1/text()')[0]
weather_day = i.xpath('li/span/img/@alt')[0]
weather_night = i.xpath('li[2]/span/img/@alt')[0]
temp_high = i.xpath('li[3]/span/text()')[0]
temp_low = i.xpath('li[4]/span/text()')[0]
wind_direction = i.xpath('li[5]/span/@title')[0]
wind_power = i.xpath('li[5]/span/text()')[0]
# 写入csv文件
writer.writerow([day, weather_day, weather_night, temp_high, temp_low, wind_direction, wind_power])
print(day, weather_day, weather_night, temp_high, temp_low, wind_direction, wind_power)
print("天气信息已写入到" + filename)
```
这个代码可以爬取辽宁省沈阳市的天气信息并将数据写入csv文件中。你可以根据需求修改url、city、filename等变量,从而爬取其他城市的天气信息并生成相应的excel文件。希望对你有所帮助!
阅读全文