'NoneType' object has no attribute 'text'
时间: 2023-08-24 16:07:49 浏览: 55
AttributeError: ‘NoneType’ object has no attribute ‘children’ 错误
5星 · 资源好评率100%
这个错误通常是因为BeautifulSoup解析出来的对象为空,没有找到对应的HTML元素,因此无法访问其text属性。你可以加入合适的错误处理来避免这个问题。以下是修改后的代码示例:
```python
import requests
from bs4 import BeautifulSoup
import re
import datetime
# 发送HTTP请求
url = 'https://tianqi.so.com/weather/101030100'
response = requests.get(url)
# 解析HTML页面
soup = BeautifulSoup(response.text, 'html.parser')
date_elem = soup.find('div', class_='date')
weather_elem = soup.find('div', class_='weather-info')
# 判断是否找到对应的HTML元素
if date_elem is None or weather_elem is None:
print('无法获取天气信息')
else:
date = date_elem.text.strip()
weather = weather_elem.text.strip()
# 提取日期和天气信息
date = re.search(r'(\d{4}年\d{1,2}月\d{1,2}日)', date).group()
weather = re.sub(r'\s+', ',', weather)
# 输出日期和天气信息
today = datetime.date.today().strftime('%Y年%m月%d日')
print(f'{today},{weather}')
```
这里我们加入了对date_elem和weather_elem是否为空的判断,如果为空则输出提示信息,否则继续进行解析和输出。
阅读全文