AttributeError:"NoneType"对象在python 3.4中没有属性"lower" [英] AttributeError: 'NoneType' object has no attribute 'lower' in python 3.4

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

问题描述

代码:

import requests
from bs4 import BeautifulSoup
import operator
def start(url):
    word_list =[]
    source_code =requests.get(url).text
    soup = BeautifulSoup(source_code)
    for post_string in soup.find_all('a',{'class':'cb-skin-ads-link'}):
        content = post_string.string
        words = content.lower()
        for each_word in words:
             print(each_word)
             word_list.append(each_word)

start('http://www.cricbuzz.com/live-cricket-scorecard/16445/gl-vs-rcb-qualifier-1-indian-premier-league-2016')

错误:

Traceback (most recent call last):
  File "C:/Users/Shera/PycharmProjects/Begin/wordcount.py", line 15, in <module>
    start('http://www.cricbuzz.com/live-cricket-scorecard/16445/gl-vs-rcb-qualifier-1-indian-premier-league-2016')
  File "C:/Users/Shera/PycharmProjects/Begin/wordcount.py", line 10, in start
    words = content.lower()
AttributeError: 'NoneType' object has no attribute 'lower'

推荐答案

要了解发生了什么,我们应该看一下

To understand what is going on, we should take a look at the documentation. There is a case when .string would be None:

如果标签包含多个内容,则不清楚.string应该指的是什么,因此.string被定义为None

If a tag contains more than one thing, then it’s not clear what .string should refer to, so .string is defined to be None

您应该考虑使用 get_text() 还要考虑元素的子元素:

You should look into using get_text() instead that would take into account the children of an element as well:

content = post_string.get_text()

请注意,这将有助于避免该错误,但是由于找到的元素实际上没有任何文本,因此您仍然不会获得任何输出:

Note that this would help to avoid the error, but you would still get no output since the element you find really does not have any text:

<a target="_blank" href="Javascript:void(0)" class="cb-skin-ads-link cb-skin-ads-link-fixed ad-skin" rel="noreferrer"></a>

这篇关于AttributeError:"NoneType"对象在python 3.4中没有属性"lower"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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