BeautifulSoup 对象 returns 作为 NoneType

BeautifulSoup object returns as NoneType

以下代码应该在 pythonscraping.com 下载徽标图像,但 returns 错误:"

AttributeError: 'NoneType' object has no attribute 'find'

”。似乎错误在于 BeautifulSoup bs 对象 returns as Nonetype。

到目前为止,使用完全相同的代码调用的所有 BeautifulSoup 个对象都可以工作。请问在这种情况下错误在哪里?谢谢

from urllib.request import urlretrieve
from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen('http://www.pythonscraping.com')
bs = BeautifulSoup(html, 'html.parser')
imageLocation = bs.find('a', {'id': 'logo'}).find('img')['src']
urlretrieve(imageLocation, 'logo.jpg')

线路错误

imageLocation = bs.find('a', {'id': 'logo'}).find('img')['src']

这是因为第二次发现 因为a标签没有找到想要的id 所以 returns None 并且你不能对 'NoneType' object

使用“find()”

如果过去使用过此代码 html 页面可能会发生变化,需要新代码