import requestsfrom bs4 import BeautifulSoup# 构造请求urlurl = 'https://www.tianqi.com/zhongmou/10/'# 发送GET请求headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.43'}response = requests.get(url,headers=headers)# 判断请求是否成功if response.status_code == 200: # 解析HTML页面 soup = BeautifulSoup(response.text, 'html.parser') # 获取天气信息 city = soup.find_all('ul class_="weaul"', class_='crumbs fl').find_all('a')[-1].text.strip() weather = soup.find_all('ul class_="weaul"', class_='wea').text.strip() temperature = soup.fin_alld('ul class_="weaul"', class_='tem').span.text.strip() wind = soup.find_all('ul class_="weaul"', class_='').i.text.strip() humidity = soup.find_all('ul class_="weaul"', class_='humidity').span.text.strip() # 将天气信息写入文本文件 with open('weather.txt', 'w', encoding='utf-8') as f: f.write(f"城市:{city}\n天气:{weather}\n温度:{temperature}\n风力:{wind}\n湿度:{humidity}")else: print("请求天气预报数据失败!")检查并修改以上程序
时间: 2024-03-31 17:35:42 浏览: 153
爬取彼岸图网的壁纸 https://pic.netbian.com/
在程序中,以下代码存在错误:
```
city = soup.find_all('ul class_="weaul"', class_='crumbs fl').find_all('a')[-1].text.strip()
weather = soup.find_all('ul class_="weaul"', class_='wea').text.strip()
temperature = soup.fin_alld('ul class_="weaul"', class_='tem').span.text.strip()
wind = soup.find_all('ul class_="weaul"', class_='').i.text.strip()
humidity = soup.find_all('ul class_="weaul"', class_='humidity').span.text.strip()
```
应将上述代码修改为:
```
city = soup.find('div', class_='crumbs fl').find_all('a')[-1].text.strip()
weather = soup.find('ul', class_='weaul').find('p', class_='wea').text.strip()
temperature = soup.find('ul', class_='weaul').find('p', class_='tem').span.text.strip()
wind = soup.find('ul', class_='weaul').find('p', class_='win').i.text.strip()
humidity = soup.find('ul', class_='weaul').find('p', class_='hum').span.text.strip()
```
修改后的代码如下:
```
import requests
from bs4 import BeautifulSoup
# 构造请求url
url = 'https://www.tianqi.com/zhongmou/10/'
# 发送GET请求
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.43'}
response = requests.get(url,headers=headers)
# 判断请求是否成功
if response.status_code == 200:
# 解析HTML页面
soup = BeautifulSoup(response.text, 'html.parser')
# 获取天气信息
city = soup.find('div', class_='crumbs fl').find_all('a')[-1].text.strip()
weather = soup.find('ul', class_='weaul').find('p', class_='wea').text.strip()
temperature = soup.find('ul', class_='weaul').find('p', class_='tem').span.text.strip()
wind = soup.find('ul', class_='weaul').find('p', class_='win').i.text.strip()
humidity = soup.find('ul', class_='weaul').find('p', class_='hum').span.text.strip()
# 将天气信息写入文本文件
with open('weather.txt', 'w', encoding='utf-8') as f:
f.write(f"城市:{city}\n天气:{weather}\n温度:{temperature}\n风力:{wind}\n湿度:{humidity}")
else:
print("请求天气预报数据失败!")
```
这样就可以正确的获取天气信息并将其写入文本文件中了。
阅读全文