Python 属性错误:';非类型';对象没有属性';属性';

Python 属性错误:';非类型';对象没有属性';属性';,python,Python,我是python新手。请帮我纠正这个错误 AttributeError:'NoneType'对象没有属性'attrs' 从bs4导入美化组 导入urllib2 导入请求 url='1〕https://www.justdial.com/Pune/Event-Organisers/nct-10194150' 请求(url,标题={'User-Agent':“Magic Browser”}) page=urllib2.urlopen(req.read)() soup=BeautifulSoup(第页

我是python新手。请帮我纠正这个错误

AttributeError:'NoneType'对象没有属性'attrs'
从bs4导入美化组
导入urllib2
导入请求
url='1〕https://www.justdial.com/Pune/Event-Organisers/nct-10194150'
请求(url,标题={'User-Agent':“Magic Browser”})
page=urllib2.urlopen(req.read)()
soup=BeautifulSoup(第页,'html.parser')
对于汤中的h.findAll('h2'):
a=h.find('a')
如果a.attrs中的“href”:
l=a.get('href')
打印l

您应该不检查
a
元素。似乎在
h2
中没有
a
标记,因此
a
NoneType

if a and 'href' in a.attrs:
    l = a.get('href')

您检查的某些元素没有,您应该确保找到的“a”元素确实具有attrs属性,您可以使用
hasattr
内置函数:

hasattr(a, "attrs")
如果有属性,则返回true;如果没有属性,则返回false。
阅读有关

使用“尝试除外”以避免
非类型
异常:

from bs4 import BeautifulSoup
import urllib2
import requests

url = 'https://www.justdial.com/Pune/Event-Organisers/nct-10194150'

req = urllib2.Request(url, headers={'User-Agent' : "Magic Browser"}) 

page = urllib2.urlopen(req).read()

soup = BeautifulSoup(page,'html.parser')

for h in soup.findAll('h2'):
    a = h.find('a')
    try:
        if 'href' in a.attrs:
            l = a.get('href')
    except:
        pass

    print l
或: 检查
a
是否为无:

from bs4 import BeautifulSoup
import urllib2
import requests

url = 'https://www.justdial.com/Pune/Event-Organisers/nct-10194150'

req = urllib2.Request(url, headers={'User-Agent' : "Magic Browser"}) 

page = urllib2.urlopen(req).read()

soup = BeautifulSoup(page,'html.parser')

for h in soup.findAll('h2'):
    a = h.find('a')

    if a is not None and 'href' in a.attrs:
        l = a.get('href')

    print l

可能重复我理解作为重复结束问题,但作为离题?很明显,想要的行为是什么,即使它的措辞不是最好的。如果我错了,请纠正我。是的,请纠正添加一个条件检查h2中是否有
a
,或者是否有类似
a=h.find('a')的内容,如果a:if'href'在a.attrs:l=get('href')print(l)
是的,谢谢,添加了一个建议检查。它起作用了。谢谢。我怎样才能使它适用于多个页面?这只适用于单个页面。请帮帮我@戈多蒂需要真实的例子来理解你的意思