| 
 | 
 
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册  
 
x
 
<ol class="tuiMusic"> 
 <li> 
  <span class="songNum"> 
   1. 
  </span> 
  <a class="play" href="/play/464446.htm" target="_self"> 
  </a> 
  <a class="songNameA" href="/play/464446.htm" target="_self"> 
   等你等了那么久 
  </a> 
  <a href="/geshou/7283.htm" target="_blank"> 
   <span class="jianNum"> 
    祁隆 
   </span> 
  </a> 
 </li> 
 <li> 
  <span class="songNum"> 
   2. 
  </span> 
  <a class="play" href="/play/637791.htm" target="_self"> 
  </a> 
  <a class="songNameA" href="/play/637791.htm" target="_self"> 
   小苹果 
  </a> 
  <a href="/geshou/18348.htm" target="_blank"> 
   <span class="jianNum"> 
    筷子兄弟 
   </span> 
  </a> 
 </li> 
 
def get_data(res): 
    soup = bs4.BeautifulSoup(res.text,"html.parser") 
    data = [] 
    targets = soup.find("ol",class_ = "tuiMusic") 
    targets = targets.find_all("li") 
    
    print(targets.prettify()) 
     
"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 'prettify'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()? 
 
就是上面的简单数据,我想遍历所有的li为什么就会出错呢。 
遇见好几次这种错误了。麻烦大佬帮忙指点。错误原因是什么,应该怎么解决呢。 
 
 
因为你是用一个ResultSet集合类型去调用的prettify()函数,所以报错了,要想正常调用,你需要对这个列表遍历,用里面的每一个元素去调用。 
修改代码如下:
 - def get_data(res):
 
 -     soup = bs4.BeautifulSoup(res.text, "html.parser")
 
 -     data = []
 
 -     targets = soup.find("ol", class_="tuiMusic")
 
 -     targets = targets.find_all("li")
 
  
-     for target in targets:
 
 -         print(target.prettify())
 
  复制代码 
 
 
 |   
 
 
 
 |