访问存在BeautifulGroup的标记的属性时发生KeyError

2024-09-28 23:22:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我的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的打印内容是

^{pr2}$

我觉得这很正常。在

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

错误是

Traceback (most recent call last): File "C:/Python27/movie comments.py", line 19, in

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

KeyError: 'data-title'

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

任何想法都会有帮助。在


Tags: importiddatatitlehtmlurllibmovieitem
1条回答
网友
1楼 · 发布于 2024-09-28 23:22:03

似乎您所获取的某些列表项不包含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)

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

相关问题 更多 >