AttributeError:' NoneType'对象没有属性' attrs'

时间:2018-03-29 11:30:55

标签: python

我是python的新手。请帮我解决这个错误。

AttributeError: 'NoneType' object has no attribute 'attrs'
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 'href' in a.attrs:
        l = a.get('href')

    print l

3 个答案:

答案 0 :(得分:3)

您应该检查a元素。似乎a中没有h2个标签,因此aNoneType

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

答案 1 :(得分:1)

使用try-except来避免NoneType例外:

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

答案 2 :(得分:0)

你检查的一些元素是无,你应该确保" a"你找到的元素实际上有attrs属性,你可以使用hasattr内置函数:

hasattr(a, "attrs")
如果a有attrs,

将返回true,否则返回false。 阅读this function