chsiwe 2022-05-03 22:58 采纳率: 50%
浏览 1192
已结题

'NoneType' object has no attribute 'string'错误

问题相关代码
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'

  • 写回答

2条回答 默认 最新

  • 溪风沐雪 2022-05-03 23:09
    关注

    看错误提示是因为p[1].find('span')没有找到这个标签,是一个空值

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • 请叫我问哥 Python领域新星创作者 2022-05-03 23:09
    关注

    HighTemprature = p[1].find('span').string
    这行语句里find('span')返回了None,也就是没有找到"span",所以不能调用后面的string属性。说明返回的网页里没有span这个标签。

    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 5月12日
  • 已采纳回答 5月4日
  • 创建了问题 5月3日

悬赏问题

  • ¥15 Qt 不小心删除了自带的类,该怎么办
  • ¥15 我需要在PC端 开两个抖店工作台客户端.(语言-java)
  • ¥15 有没有哪位厉害的人可以用C#可视化呀
  • ¥15 可以帮我看看代码哪里错了吗
  • ¥15 设计一个成绩管理系统
  • ¥15 PCL注册的选点等函数如何取消注册
  • ¥15 问一下各位,为什么我用蓝牙直接发送模拟输入的数据,接收端显示乱码呢,米思齐软件上usb串口显示正常的字符串呢?
  • ¥15 Python爬虫程序
  • ¥15 crypto 这种的应该怎么找flag?
  • ¥15 代码已写好,求帮我指出错误,有偿!