1. 程式人生 > >python從入門到放棄

python從入門到放棄

學習Python網路資料採集時,講到標籤的查詢

from bs4 import BeautifulSoup
from urllib.request import urlopen
import re
html = urlopen('http://www.pythonscraping.com/pages/page3.html')
bsObj = BeautifulSoup(html,"html.parser")
children =  bsObj.findAll('table',{'id':'giftList'}).tr.next_siblings
for child in children:
    print
(child)

因為一直在想findAll()和find()的區別,於是就改了一下程式碼,發現報錯。

Traceback (most recent call last):
  File "G:/python/reptile/test.py", line 6, in <module>
    children =  bsObj.findAll('table',{'id':'giftList'}).tr.next_siblings
  File "G:\Users\DELL\python\lib\site-packages\bs4\element.py", line 1807, in __getattr__
    "ResultSet object has no attribute '%s'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?" % key

AttributeError: ResultSet object has no attribute 'tr'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?

然後查了一下百度發現有人和我一樣的。然後瞭解到:

物件的方法find_all()返回的是一個結果集列表,而結果集列表是一組資料,其是沒有屬性的,只有單個數據物件才有屬性可言。

應該使用find().children,而soup.find()返回的結果一個字串物件,其可以存在屬性的呼叫。


原網址:https://www.cnblogs.com/my1e3/p/6680476.html