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))
原文地址:https://www.cnblogs.com/my1e3/p/6680476.html