簡體   English   中英

錯誤:AttributeError:'NoneType' object 沒有屬性 'find'

[英]Error: AttributeError: 'NoneType' object has no attribute 'find'

我正在編寫網頁抓取代碼,但出現上述錯誤。

import requests
import lxml
import bs4

title = ''
date = ''
text = ''
top = []
link = []  


web_link = 'https://timesofindia.indiatimes.com/{}/'
web_link = web_link.format('india')
req = requests.get(web_link)
soup = bs4.BeautifulSoup(req.text, 'lxml')
topi = soup.find('div', {'class':'main-content'})
topi = topi.find_all('span', {'class':'w_tle'})
for i in range(len(topi)):
   top = topi[i].find('a').get('href')
   link.append('https://timesofindia.indiatimes.com' + top)
for i in range(len(link)):
   rq = requests.get(link[i])
   sp = bs4.BeautifulSoup(rq.text, 'lxml')
   title = sp.find('div', {'class':'_2NFXP'})
   title = title.find('h1',{'class':'_23498'})

追溯:

Traceback (most recent call last):
  File "C:\Users\xxx\xxx\py\so65702068.py", line 26, in <module>
    title=title.find('h1',{'class':'_23498'})
AttributeError: 'NoneType' object has no attribute 'find'

我是 web 抓取的新手,我不明白為什么它會顯示此錯誤。

您應該嘗試自己從錯誤中學習。 Python 錯誤還指定錯誤的位置(行)。

無論如何,你的最后一行導致了問題。 您基本上在另一個 sp.find( sp.find() function 上應用了sp.find() function。 由於sp.find('div',{'class':'_2NFXP'})返回None ,它證明了你得到的錯誤是正確的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM