python 报错keyerror_python,_python 爬取 KeyError,python - phpStudy

python 爬取 KeyError

from html.parser import HTMLParser

import urllib.request

with urllib.request.urlopen('https://www.python.org/events/python-events/') as url:

content = url.read()

html = content.decode('utf-8')

class MyHtmlParser(HTMLParser):

def __init__(self):

HTMLParser.__init__(self)

self.location = []

self.flag = False

def handle_starttag(self, tag, attrs):

if tag == 'span' and 'event-location' in dict(attrs)['class']:

self.flag = True

def handle_data(self, data):

if self.flag:

self.location.append(data)

self.flag = False

parser = MyHtmlParser()

parser.feed(html)

for i in parser.location:

print(i)

运行结果:

Traceback (most recent call last):

File "C:/Users/user/PycharmProjects/untitled1/python6.py", line 22, in

parser.feed(html)

File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\html\parser.py", line 111, in feed

self.goahead(0)

File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\html\parser.py", line 171, in goahead

k = self.parse_starttag(i)

File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\html\parser.py", line 345, in parse_starttag

self.handle_starttag(tag, attrs)

File "C:/Users/user/PycharmProjects/untitled1/python6.py", line 14, in handle_starttag

if tag == 'span' and 'event-location' in dict(attrs)['class']:

KeyError: 'class'

为什么会有KeyError呢?

这是爬取的目标网站的一段代码:

Capital One McLean Conference Center in McLean, VA, USA

没有大小写错误,怎么会有KeyError呢?

另外我爬取这一段代码:

PyConES 2016 - Almeria

把代码改成if tag == 'a' and 'python-event' in dict(attrs)['href']:

就可以成功爬取。。。

所以是什么问题呢?

是class有禁忌????

相关阅读:

扩展关键字let在firefox表现不一致

Python中aysncio的事件循环是属于线程还是进程?

javascript 对象属性预加载问题

jQuery事件绑定已存在声明函数时如何更优雅?

使用RxJs碰到的问题,如何防止重复订阅?

angular2组件传值

如何利用framework7切换页面的

-webkit-box-sizing属性冲突如何解决

Chrome不能打开本地html文件?

linux安装php 模块--with-mysql --with-mysqli非得需要安装mysql吗

Jquery对象默认值问题求助,实现传参后覆盖默认值

vue页面如何不互相影响

vue.js中v-bind:class没效果?

队列设计问题

类似微博首页,一张图的时候是如何确定图大小的?

一段函数执行的两次结果

Laravel中的门面(Facades)有什么意义?

npm start 之后出现问题

你们有没有bmob平台的公告源码项目?

关于vr和前端的问题

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值