发生异常:AttributeError: 'NoneType' object has no attribute 'attrs'

发生异常: AttributeError
AttributeError: 'NoneType' object has no attribute 'attrs'

以下为具体代码:

# TODO 使用import导入requests模块
import requests

# TODO 使用from...import从bs4模块中导入BeautifulSoup
from bs4 import BeautifulSoup

# TODO 将URL"https://nocturne-spider.baicizhan.com/practise/19.html"赋值给变量url
url = "https://nocturne-spider.baicizhan.com/practise/19.html"

# 将User-Agent以字典键对形式赋值给headers
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"}

# TODO 使用get()函数请求链接,并且带上headers
response = requests.get(url,headers = headers)

# TODO 使用.text属性将服务器相应内容转换为字符串形式,赋值给html
html = response.text

# TODO 使用BeautifulSoup()传入变量html和解析器lxml,赋值给soup
soup = BeautifulSoup(html,"lxml")

# TODO 使用find_all()查询soup中class="item"的节点,赋值给content_all
content_all = soup.find_all(class_="item")

# TODO for循环遍历content_all
for content in content_all:

    # TODO 使用find()查询content中的img标签,并赋值给imgContent
    imgContent = content.find(name="img")

    # TODO 使用.attrs获取data-src对应的属性值,并赋值给imgSrc
    imgSrc = imgContent.attrs["data-src"]

    # TODO 将url和imgSrc以字符串形式相连接,赋值给imgUrl
    imgUrl = url + imgSrc

    # TODO 输出imgUrl
    print(imgUrl)


```r: 'NoneType' object has no attribute 'attrs'



报错具体内容如下:
发生异常: AttributeError
'NoneType' object has no attribute 'attrs'
  File "C:\Users\31088\Desktop\py数据\摄影作品.py", line 32, in <module>
    imgSrc = imgContent.attrs["data-src"]
AttributeError: 'NoneType' object has no attribute 'attrs'


参考GPT和自己的思路:这个错误的原因是在使用content.find(name="img")查找img标签时,有些节点中没有img标签,因此返回的值为None,而None又没有attrs属性,因此会报错'NoneType' object has no attribute 'attrs'。因此,在使用imgContent.attrs["data-src"]获取属性值之前,应该先判断imgContent是否为None。可以使用if语句进行判断,例如:

if imgContent is not None:
    imgSrc = imgContent.attrs["data-src"]
else:
    imgSrc = ""

这样,如果imgContent为None,则将imgSrc赋值为空字符串,避免了报错。

参考GPT和自己的思路:这个问题的原因是在执行imgContent = content.find(name="img")时没有找到对应的img标签节点,因此imgContent的值为None,导致后面使用imgContent.attrs["data-src"]时报错。你可以在使用imgContent.attrs["data-src"]前加入一个if判断来避免这个问题的发生,如下所示:

imgContent = content.find(name="img")
if imgContent:
    imgSrc = imgContent.attrs["data-src"]
    imgUrl = url + imgSrc
    print(imgUrl)

这样就可以避免使用None对象的属性而导致的异常了。

imgContent是个None,很显然find的时候没有找到

需要判断一下

img