访问存在的标记属性时的KeyError - BeautifulSoup

时间:2017-08-19 03:37:54

标签: python beautifulsoup

我的python版本是2.7

# -*- coding : utf - 8 -*-
import urllib
from bs4 import BeautifulSoup

resp = urllib.urlopen('https://movie.douban.com/nowplaying/hangzhou')
html_data = resp.read().decode('utf-8')

soup = BeautifulSoup(html_data,'html.parser')
nowplaying_movie = soup.find_all('div',id = 'nowplaying')
print nowplaying_movie
# notice class_
nowplaying_movie_list = nowplaying_movie[0].find_all('li',class_ = 'list-item')
print nowplaying_movie_list

nowplaying_list = []
for item in nowplaying_movie_list :
    nowplaying_dict = {}
    nowplaying_dict['id'] = item['id']
    nowplaying_dict['name'] = item['data-title']
    nowplaying_movie_list.append(nowplaying_dict)

nowplaying_movie_list的打印内容为

[<li class="list-item" data-actors="\u53e4\u5929\u4e50 / \u5434\u6a3e / \u6258\u5c3c\xb7\u8d3e" data-category="nowplaying" data-director="\u53f6\u4f1f\u4fe1" data-duration="101\u5206\u949f" data-enough="True" data-region="\u9999\u6e2f \u4e2d\u56fd\u5927\u9646" data-release="2017" data-score="7.5" data-showed="True" data-star="40" data-subject="26826398" data-title="\u6740\u7834\u72fc\xb7\u8d2a\u72fc" data-votecount="11357" id="26826398">\n<ul class="">\n<li class="poster">\n<a class="ticket-btn" data-psource="poster" href="https://movie.douban.com/subject/26826398/?from=playing_poster" target="_blank">\n<img alt="\u6740\u7834\u72fc\xb7\u8d2a\u72fc" class="" rel="nofollow" src="https://img3.doubanio
我觉得这很正常。

我想在网站上提取电影的ID和名称并将其保存到dict中,但错误表明“数据标题”有问题。

错误是

  

Traceback(最近一次调用最后一次):文件“C:/ Python27 / movie   comments.py“,第19行,

     

nowplaying_dict ['name'] = item ['data-title']

     

KeyError:'data-title'

我想这是识别hyphen的问题,因为我很确定在打印的html文件中存在类“data-title”。

任何想法都会有所帮助。

1 个答案:

答案 0 :(得分:0)

您搜索的某些列表项似乎不包含data-title属性。其他所有内容都会检出,那么为什么不只是catch那个例外?

nowplaying_list = []
for item in nowplaying_movie_list:
    try:
        nowplaying_dict = {}
        nowplaying_dict['id'] = item['id']
        nowplaying_dict['name'] = item['data-title']
        nowplaying_list.append(nowplaying_dict)
    except KeyError:
        pass

print(nowplaying_list)

另外,我注意到你要附加到错误的列表中。