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

'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')没有找到这个标签,是一个空值

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

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

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本