python爬虫之异常捕获及标签过滤详解

今天带大家了解python异常捕获及标签过滤,文中有非常详细的代码示例,对正在学习python爬虫的小伙伴们很有帮助,需要的朋友可以参考下

增加异常捕获,更容易现问题的解决方向

 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()}') 

运行后的结果显示如下:

 电影评价数:(38054人评价) 电影评价数:(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"})

以上就是python爬虫之异常捕获及标签过滤详解的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » python