问题相关代码
from bs4 import BeautifulSoup
import requests
response = requests.get('http://www.weather.com.cn/weather/101280101.shtml')#发起网络请求(访问网址)
response.encoding = 'utf-8'#设置编码为utf-8
soup = BeautifulSoup(response.text,'html.parser')
div = soup.find('div',id = '7d')#获取id=7d的div标签的内容
ul = div.find('ul')#获取div标签中第一个ul标签的内容
li = ul.find_all('li')#获取ul标签中所有li标签的内容
weatherForSevenDay = []
for weather in li:
temp = []
date = weather.find('h1').string#获取li标签中h1标签的内容
temp.append(date)
p = weather.find_all('p')#获取li标签中所有p标签的内容
weatherDetail = p[0].string#获取第一个p标签的内容
if weatherDetail is not None:
temp.append('天气为:%s'%weatherDetail)
HighTemprature = p[1].find('span').string#获取第二个p标签中span标签的内容
if HighTemprature is not None:
temp.append('最高温为%s°C'%HighTemprature)
LowTemprature = p[1].find('i').string#获取第二个p标签中i标签的内容
if LowTemprature is not None:
temp.append('最低温为%s°C'%LowTemprature)
weatherForSevenDay.append(temp)
for weather in weatherForSevenDay:
print(weather)
######报错
Traceback (most recent call last):
File "C:\Users\DELL\Documents\Aptana Studio 3 Workspace\python\my\广州七日天气.py", line 19, in
HighTemprature = p[1].find('span').string#获取第二个p标签中span标签的内容
AttributeError: 'NoneType' object has no attribute 'string'