python爬虫之异常捕获及标签过滤详解
作者:一名小测试 时间:2021-08-10 07:32:06
增加异常捕获,更容易现问题的解决方向
import ssl
import urllib.request
from bs4 import BeautifulSoup
from urllib.error import HTTPError, URLError
def get_data(url):
headers = {"user-agent":
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36"
}
ssl._create_default_https_context = ssl._create_unverified_context
"""
urlopen处增加两个异常捕获:
1、如果页面出现错误或者服务器不存在时,会抛HTTP错误代码
2、如果url写错了或者是链接打不开时,会抛URLError错误
"""
try:
url_obj = urllib.request.Request(url, headers=headers)
response = urllib.request.urlopen(url_obj)
html = response.read().decode('utf8')
except (HTTPError, URLError)as e:
raise e
"""
BeautifulSoup处增加异常捕获是因为BeautifulSoup对象中有时候标签实际不存在时,会返回None值;
因为不知道,所以调用了就会导致抛出AttributeError: 'NoneType' object has no xxxxxxx。
"""
try:
bs = BeautifulSoup(html, "html.parser")
results = bs.body
except AttributeError as e:
return None
return results
if __name__ == '__main__':
print(get_data("https://movie.douban.com/chart"))
解析html,更好的实现数据展示效果
get_text():获取文本信息
# 此处代码同上面打开url代码一致,故此处省略......
html = response.read().decode('utf8')
bs = BeautifulSoup(html, "html.parser")
data = bs.find('span', {'class': 'pl'})
print(f'电影评价数:{data}')
print(f'电影评价数:{data.get_text()}')
运行后的结果显示如下:
电影评价数:<span class="pl">(38054人评价)</span>
电影评价数:(38054人评价)
find() 方法是过滤HTML标签,查找需要的单个标签
实际find方法封装是调用了正则find_all方法,把find_all中的limt参数传1,获取单个标签
1.name:可直接理解为标签元素
2.attrs:字典格式,放属性和属性值 {"class": "indent"}
3.recursive:递归参数,布尔值,为真时递归查询子标签
4.text:标签的文本内容匹配 , 是标签的文本,标签的文本
find_all() 方法是过滤HTML标签,查找需要的标签组
使用方法适合find一样的,无非就是多了个limit参数(筛选数据)
必须注意的小知识点:
# 下面两种写法,实际是一样的功能,都是查询id为text的属性值
bs.find_all(id="text")
bs.find_all(' ', {"id": "text"})
# 如果是class的就不能class="x x x"了,因为class是python中类的关键字
bs.find_all(class_="text")
bs.find_all(' ', {"class": "text"})
来源:https://blog.csdn.net/LIFENG0402/article/details/116754853
标签:python,异常捕获,标签过滤
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
SWF FLASH的param属性参数详解
2008-10-25 15:12:00
snoopy PHP版的网络客户端提供本地下载
2023-06-28 00:09:55
用户体验 保守的使用下拉菜单
2008-01-15 20:00:00
解决Keras TensorFlow 混编中 trainable=False设置无效问题
2022-10-23 16:56:19
php输出文字乱码的解决方法
2023-11-11 07:40:08
Python实战之实现康威生命游戏
2022-06-30 14:21:12
![](https://img.aspxhome.com/file/2023/7/109457_0s.png)
Oracle新建用户、角色,授权,建表空间的sql语句
2012-07-11 15:39:24
Python实现字符串与数组相互转换功能示例
2021-08-13 15:50:12
![](https://img.aspxhome.com/file/2023/3/76883_0s.jpg)
关于python中逆序的三位数
2021-08-09 05:17:28
![](https://img.aspxhome.com/file/2023/8/80588_0s.jpg)
python 实现控制鼠标键盘
2023-08-04 09:37:56
详解pandas删除缺失数据(pd.dropna()方法)
2021-03-26 04:36:33
![](https://img.aspxhome.com/file/2023/8/115098_0s.png)
widows下安装pycurl并利用pycurl请求https地址的方法
2023-07-09 03:21:18
![](https://img.aspxhome.com/file/2023/4/61204_0s.jpg)
python基于scrapy爬取京东笔记本电脑数据并进行简单处理和分析
2023-08-05 03:18:06
![](https://img.aspxhome.com/file/2023/2/72252_0s.png)
python3发送邮件需要经过代理服务器的示例代码
2023-07-27 01:00:44
Python实现 PS 图像调整中的亮度调整
2021-04-02 20:08:54
python基础之递归函数
2021-11-29 03:28:30
![](https://img.aspxhome.com/file/2023/8/93538_0s.png)
OpenCV-PS扩散毛玻璃效果的实现代码
2022-03-17 22:45:52
![](https://img.aspxhome.com/file/2023/1/117551_0s.jpg)
AJAX缓存问题的两种解决方法(IE)
2008-05-02 20:57:00
Python使用scapy模块发包收包
2021-04-26 16:32:12
![](https://img.aspxhome.com/file/2023/9/69429_0s.jpg)
960网格系统
2009-02-17 12:22:00
![](https://img.aspxhome.com/file/UploadPic/20092/17/960-grid-system-092-54s.jpg)