我是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
答案 0 :(得分:3)
您应该检查a
元素。似乎a
中没有h2
个标签,因此a
为NoneType
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