python 學習之FAQ:find 與 find_all 使用


 

FAQ記錄

 

1. 錯誤源碼

錯誤源碼如下

    def fillUnivList(_html,_ulist):
    soup =BeautifulSoup(_html,'html.parser')
    for tr in soup.find_all('tbody').children:
    if isinstance(tr,bs4.element.Tag):
    tds = tr.find_all('td')
    _ulist.append((tds[0].string,tds[1].string,tds[3].string))

 

2. 報錯顯示

運行報錯顯示

1     File"printUnivLst.py", line 26,in getUnivList
2     for tr in soup.find_all('tbody').children:#注意find與find_all不同使用場景
3     AttributeError:'ResultSet' object has no attribute 'children'

3. 報錯分析

  報錯內容AttributeError: 'ResultSet' object has no attribute 'children'意思為屬性錯誤:結果集對象每一屬性可以調用。

  分析錯誤源碼既可以知道soup對象的方法find_all()返回的是一個結果集列表,而結果集列表是一組數據,其是沒有屬性的,只有單個數據對象才有屬性可言。

  故,原錯誤源碼中,對於tbody標簽的子標簽內容進行查找時,應該使用find().children,而soup.find()返回的結果一個字符串對象,其可以存在屬性的調用。

4. 修改的代碼

1     # 大學排名數據提取,並存入列表
2     def getUnivList(_html,_Univlst):
3     soup =BeautifulSoup(_html,'html.parser')
4     for tr in soup.find('tbody').children:#注意find 與find_all不同使用場景
5     if isinstance(tr,bs4.element.Tag):
6     tds = tr.find_all('td')
7     _Univlst.append((tds[0].string,tds[1].string,tds[3].string))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM