python中的NoneType [英] NoneType in python

查看:50
本文介绍了python中的NoneType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图从 Tripadvisor获得一些评级数据,但是当我尝试获取数据时

I was trying to get some rating data from Tripadvisor but as i was trying to fetch the data i was getting

"NoneType"对象不可下标

'NoneType' object is not subscriptable

有人可以帮我弄清楚我要去哪里哪里吗,对不起,我是python的新手.

Can anybody help me figuring out where am i going wrong , sorry i am very new to python.

这是我的示例代码

import requests
import re
from bs4 import BeautifulSoup
r = requests.get('http://www.tripadvisor.in/Hotels-g186338-London_England-Hotels.html')
data = r.text        
soup = BeautifulSoup(data)
for rate in soup.find_all('div',{"class":"rating"}):
               print (rate.img['alt'])

输出如下:

4.5 of 5 stars
4.5 of 5 stars 4 of 5 stars
4.5 of 5 stars
4.5 of 5 stars 4 of 5 stars
4.5 of 5 stars
4.5 of 5 stars
4.5 of 5 stars Traceback (most recent call last):

  File "<ipython-input-52-7460e8bfcb82>", line 3, in <module>
    print (rate.img['alt'])

TypeError: 'NoneType' object is not subscriptable

推荐答案

并非您的所有< div class ="rating"> 标记都具有< img/> 标记,因此 rate.img None .

Not all your <div class="rating"> tags have an <img /> tag, so rate.img is None.

这些div看起来像这样:

Those divs look like this instead:

<div class="rating">
  <span class="rate">4.5 out of 5, </span>
  <em>2,294 Reviews</em>
  <br/>
  <div class="posted">Last reviewed 25 Sep 2015</div>
</div>

您可以对此进行测试:

if rate.img is not None:
    # ...

或仅选择 div.rating 标签下带有 CSS选择器:

for img in soup.select('div.rating img[alt]'):

此处的选择器选择带有 alt 属性的< img/> 标签,该标签嵌套在< div class ="rating">标记.

The selector here picks out <img/> tags with an alt attribute, nested inside a <div class="rating"> tag.

这篇关于python中的NoneType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆