无输入 python

NoneType in python

我试图从 Tripadvisor 获取一些评分数据,但当我试图获取数据时,我得到的是

'NoneType' object is not subscriptable

任何人都可以帮我弄清楚我哪里出错了,抱歉我是 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

这意味着并非所有 class 为 ratingdiv 都具有具有 alt 属性的图像。你应该适当地处理这个 - 要忽略这种情况,只需将你的 print (rate.img['alt']) 包装在一个 try 中,except 块,或者先检查 rate.img 是否是 None

第一个选项:

try:
    print(rate.img['alt'])
except TypeError:
    print('Rating error')

第二个选项:

for rate in soup.find_all('div',{"class":"rating"}):
    if rate.img is not None:
        print (rate.img['alt'])

第一个选项在 EAFP (Easier to ask for forgiveness than permission), a common Python coding style, whereas the second follows LBYL 之后(三思而后行)。在这种情况下,我会建议第二种。

并不是所有的 <div class="rating"> 标签都有 <img /> 标签,所以 rate.imgNone

那些 div 看起来像这样:

<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:
    # ...

或 select 仅 div.rating 标签下带有 CSS selector:

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

selector 在这里挑选出具有 alt 属性的 <img/> 标签,嵌套在 <div class="rating"> 标签内。