你知道爲什麼在BeautifulSoup教程http://www.crummy.com/software/BeautifulSoup/documentation.html#QuickStart第一個例子給AttributeError: 'NavigableString' object has no attribute 'name'
?根據this answer在HTML中的空格字符導致問題。我嘗試了幾頁的來源,其中1人工作,其他人給了同樣的錯誤(我刪除了空格)。你能解釋一下「名稱」是指什麼以及爲什麼會發生這種錯誤?謝謝。BeautifulSoup:AttributeError的:「NavigableString」對象有沒有屬性「名」
9
A
回答
13
name
將參考標記的名稱如果對象是一個Tag
對象(即:<html>
名=「HTML」),如果你有在節點之間在您的標記空間BeautifulSoup將會把這些變成NavigableString
的。所以,如果你使用contents
的索引節點搶,你可能會搶NavigableString
,而不是下一個Tag
。
爲了避免這種情況,請查詢節點您正在尋找:Searching the Parse Tree
,或者如果你知道你想下一個標籤的名稱,你可以使用該名稱作爲屬性,它會返回第一個Tag
與名稱或None
如果沒有孩子這個名字存在:Using Tag Names as Members
如果你想使用contents
你必須檢查你正在使用的對象。你所得到的錯誤只是意味着你正在嘗試,因爲代碼假定它是一個Tag
5
您可以使用try catch來消除情況下,當通航字符串在循環被解析,這樣訪問name屬性:
for j in soup.find_all(...)
try:
print j.find(...)
except NavigableString:
pass
3
不理會NavigableString
對象,同時通過樹遍歷:
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
for body_child in soup.body.children:
if isinstance(body_child, NavigableString):
continue
if isinstance(body_child, Tag):
print(body_child.name)
相關問題
- 1. BeautifulSoup:AttributeError:'NavigableString'對象沒有屬性'children'
- 2. AttributeError:'NavigableString'對象沒有屬性'find_all'(NameError)
- 3. BeautifulStoneSoup AttributeError的:「NavigableString」對象有沒有屬性「子標籤」
- 4. BeautifulSoup +請求>> AttributeError:'NavigableString'對象沒有屬性'find_all'
- 5. BS4 + Python3:無法抓取樹:'NavigableString'對象沒有屬性'has_attr'
- 6. AtributeError:int對象有沒有屬性名
- 7. 名單'對象有沒有屬性「帶」
- 8. 沒有對象的屬性名
- 9. BeautifulSoup:AttributeError:'str'對象沒有屬性'copy'。在Ubuntu上運行,在Windows上失敗
- 10. AttributeError的: '名單' 對象有沒有屬性 '對象'
- 11. 'CheckoutView' 對象有沒有屬性 '對象'
- 12. 'ProfileManager'對象沒有屬性'用戶名'
- 13. Queryset對象沒有屬性「名稱」
- 14. 'collections.OrderedDict'對象沒有屬性'用戶名'
- 15. 「remoteContext對象沒有屬性」
- 16. 對象沒有屬性'count'
- 17. 'MarkovGenerator'對象沒有屬性'
- 18. 對象沒有屬性questionNum
- 19. 對象沒有屬性
- 20. 「RelatedManager」對象沒有屬性
- 21. Django對象沒有屬性
- 22. 對象沒有屬性 - HyperlinkedRelatedField
- 23. 對象沒有屬性_Message__decoded_fields
- 24. Django'settings'對象沒有屬性
- 25. 對象沒有屬性
- 26. 對象沒有屬性'get_absolute_url'
- 27. Python:對象沒有屬性
- 28. Tkinter對象沒有屬性
- 29. 對象沒有屬性'result_count'
- 30. 對象沒有屬性'get'
.find_all()似乎只返回子標籤,而忽略空格... –