[英]Why am I getting this Attribute error when there is data there?
我正在通過NewBoston教程制作一個詞頻計算器。 它首先從網頁上獲取文本,然后將其清理並計算單詞數。 我處於第一階段,將文字從頁面上刮下來:
def start(url):
word_list = []
source_code = requests.get(url, verify=True).text
soup = BeautifulSoup(source_code)
for page_text in soup.find_all('p'):
content = page_text.string
print(content)
words = content.lower().split()
for each_word in words:
word_list.append(each_word)
運行它時,出現以下錯誤:
Traceback (most recent call last):
File "C:/Users/user/PycharmProjects/NewBostonTuts/WordFrequency.py", line 30, in <module>
start('https://www.example.com')
File "C:/Users/user/PycharmProjects/NewBostonTuts/WordFrequency.py", line 13, in start
words = content.lower().split()
AttributeError: 'NoneType' object has no attribute 'lower'
這向我暗示它沒有任何content
可以使用,但是如您所見,在嘗試lower()
和split()
content
之前,我先打印出content
然后按預期輸出-顯示所有<p>
標記內容。
是什么賦予了?
使用tag.text
代替tag.string
。 tag.string
是NavigableString ,如果標記不包含文本,則類型可以為NoneType
,而在這種情況下, tag.text
包含長度為0的字符串。
tag.string
便利屬性,用於獲取此標記內的單個字符串。
:Return:如果此標記具有單個字符串子代,則返回值為該字符串。 如果此標記沒有子項,或者有多個子項,則返回值為None。 如果此標簽具有一個子標簽,則遞歸返回值是該子標簽的'string'屬性。
這是該屬性的實現
if len(self.contents) != 1:
return None
child = self.contents[0]
if isinstance(child, NavigableString):
return child
return child.string
tag.text
使用Python 2.7.4:
>>> a=None
>>> print(a)
None
>>> a.lower()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'lower'
即使a為None,print也會使用str()將其轉換,這就是為什么print()調用不會失敗的原因:
>>> a
>>> str(a)
'None'
如果深入研究,則定義了None類型的str ,這是在調用print()期間由str()調用的:
>>> dir(None)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.