并将其生成一个本地网址
时间: 2024-04-01 10:35:07 浏览: 21
好的,以下是将2345天气网嘉兴市10天内天气数据生成本地网页的示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 设置请求头
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'}
# 发送请求
url = 'https://tianqi.2345.com/jiaxing/58457.htm'
response = requests.get(url, headers=headers)
# 解析HTML内容
soup = BeautifulSoup(response.content, 'html.parser')
# 获取天气信息
weather_info = soup.find_all('li', class_='li')
# 生成HTML文件
with open('jiaxing_weather.html', 'w', encoding='utf-8') as f:
f.write('<html>')
f.write('<head><title>嘉兴市未来10天天气预报</title></head>')
f.write('<body>')
f.write('<h1>嘉兴市未来10天天气预报</h1>')
f.write('<table>')
f.write('<tr><th>日期</th><th>星期</th><th>天气</th><th>温度</th><th>风向</th></tr>')
for weather in weather_info[:10]:
date = weather.find('span', class_='date').text
week = weather.find('span', class_='week').text
wea = weather.find('span', class_='wea').text
tem = weather.find('em').text
win = weather.find('span', class_='win').text
f.write(f'<tr><td>{date}</td><td>{week}</td><td>{wea}</td><td>{tem}</td><td>{win}</td></tr>')
f.write('</table>')
f.write('</body>')
f.write('</html>')
print('文件已生成:jiaxing_weather.html')
```
上述代码中,我们将爬取的天气数据按照HTML格式写入本地文件jiaxing_weather.html中,并在文件中插入表格以展示天气数据。最后输出“文件已生成:jiaxing_weather.html”以提示文件已经生成成功。您可以在浏览器中打开生成的本地文件,查看嘉兴市未来10天的天气预报。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)