首页 > 解决方案 > 我如何解决''NoneType'对象不可下标'

问题描述

我正在编写一个用于抓取的小脚本,但遇到了错误“TypeError:'NoneType' 对象不可下标。

我以前从未见过这个错误,所以我不知道它是什么意思。

import bs4
import requests

myUrl = "https://www.houzz.com/professionals/searchDirectory? topicId=11785&query=Interior+Designers+%26+Decorators&location=Texas&distance=0&sort=4"                                                
data=requests.get(myUrl)
soup=bs4.BeautifulSoup(data.text,'html.parser')
listing = soup.find_all('div', class_="hz-pro-search-result__profile- desc")
for li in listing:
  myurl = li
  res = myurl.a['href']
  print(res)

错误:

File "C:\Users\Hp\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/Hp/.spyder-py3/houzz.py", line 20, in <module>
res = myurl.a['href']

TypeError: 'NoneType' object is not subscriptable

标签: pythonbeautifulsoup

解决方案


我的 URL 可能正在返回None,因此您无能为力。使用这样的类检查此 div 中的 li 对象的 HTML 代码。我认为 y 不存在


推荐阅读