Python的BeautifulSoup之find和find_all

这篇博客探讨了在使用BeautifulSoup进行Python爬虫时遇到的问题,即对find和find_all方法的理解不足。错误源于将ResultSet对象当作单个元素处理。文章提醒,当预期只有一项结果时,使用find_all并限制返回数量(如limit=1)不如直接使用find方法。find_all找不到目标时返回空列表,而find找不到则返回None。
摘要由CSDN通过智能技术生成

今天学习写爬虫,练习网址为http://blog.csdn.net/bo_wen_/article/details/50868339,做一个抓取每日最高最低温度的练习。在过程中遇到这样一个问题,代码所示:

# coding : UTF-8
import requests
from bs4 import BeautifulSoup
res = requests.get('http://www.weather.com.cn/weather/101190401.shtml')
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text,"html5lib")
tt=soup.body.find_all('ul',class_= 't clearfix')
tt2 = tt.find_all('li')
print(tt2)
运行结果如下:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-60-2de0ac4bc00d> in <module>()
     14 
     15 tt=soup.body.find_all('ul',class_= 't clearfix')
---> 16 tt2 = tt.find_all('li')
     17 print(tt2)

D:\folder\envs\hh\lib\site-packages\bs4\element.py in __getattr__(self, key)
   1805     def __getattr__(self, key):
   1806         raise AttributeError(
-> 1807             "ResultSet object has no attribute '%s'. Yo

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值