'''灵活又方便的网页解析库,处理高效,支持多种解析器。利用它不用编写正则表达式即可方便的实现网页信息的提取。'''

BeautifulSoup库包含的一些解析库:

解析库      使用方法              优势                              劣势

python标准库   BeautifulSoup(markup,"html.parser")  python内置标准库、执行速度适中、文档容错能力强         python 2.7.0 or 3.2.2前的版本中文容错能力差

lxml HTML解析库  BeautifulSoup(markup,"lxml")      速度快、文档容错能力强                     需要安装C语言库

lxml XML解析库  BeautifulSuop(markup,"xml")       速度快、唯一支持XML的解析库                  需要安装C语言库

html5lib        BeautifulSoup(markup,"html5lib")     最好的容错性、以浏览器的方式解析文档、生成HTML5格式的文档   速度慢、不依赖外部扩展

'''基本使用'''
html = '''
<html lang="zh-cn">
<head>
<title>翱游 - 博客园</title>
</head>
<body>
<p class="tab" name="morning">
good night
<a name="top" href="http://www.123.com">
<span>wisir</span>
</a>
<a href="hello.cn">hh</a>
<a href="man.cn">man</a>
</p>
<p class="cp" name="dromouse">hello,world</p>
<p>...</p>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html,"lxml")
print(soup.prettify()) #自动格式化输出与补全代码 '''标签选择器'''
print("-标签选择器-"*20)
#选择元素:返回匹配的第一个元素
print(type(soup.title),soup.title)
print(soup.p)
#获取名称
print(soup.title.name)
#获取属性
print(soup.p.attrs['name'])
print(soup.p['name'])
#获取内容
print(soup.title.string)
#嵌套选择
print(soup.head.title.string)
#子节点和子孙节点
print(soup.p.contents) #返回以子节点为元素的列表
print(soup.p.children) #.children得到的是一个迭代器对象,.contents得到的是一个列表
for i,child in enumerate(soup.p.children):
print(i,child)
print(soup.p.descendants) #.descendants获取所有的子孙节点
for i,child in enumerate(soup.p.descendants):
print(i,child)
#父节点和祖先结点
print(soup.a.parent) #输出父节点
print(list(enumerate(soup.a.parents))) #输出祖先结点,层层向上
#兄弟节点
print(list(enumerate(soup.a.next_siblings))) #输出所有的后兄弟节点
print(list(enumerate(soup.a.previous_siblings))) #输出所有的前兄弟节点
'''find_all(name,attrs,recursive,text,**kwargs):可根据标签名、属性、内容查找文档'''
print("-find_all-"*20)
html = '''
<div class="panel">
<div class="panel-heading">
<h4>Hello</h4>
</div>
<div class="panel-body">
<ul class="list" id="list-1" name="element">
<li class="element">Foo</li>
<li class="element">Bar</li>
<li class="element">Jay</li>
</ul>
<ul class="list list-small" id="list-2">
<li class="element">Foo</li>
<li class="element">Bar</li>
</ul>
</div>
</div>
'''
soup = BeautifulSoup(html,"lxml")
#name
print(soup.find_all('ul'))
print(type(soup.find_all("ul")[0]))
#attrs
print(soup.find_all(attrs={"id":"list-1"}))
print(soup.find_all(attrs={"name":"element"}))
#text
print(soup.find_all(text="Foo")) '''find(name,attrs,recursive,text,**kwargs):返回find_all方法的第一个元素'''
print(soup.find("ul")) '''
find_parents()与find_parents
find_next_siblings()与find_next_sibling()
find_previous_siblings()与find_previous_sibling()
find_all_next()与find_next()
find_all_previous()和find_previous()
同find_all()与find()
''' '''CSS选择器'''
print("-CSS选择器-"*20)
#通过select直接传入CSS选择器即可完成选择,返回符合要求的所有结果为元素的列表
print(soup.select('.panel .panel-heading')) #类选择器前加.,层级选择器之间加空格
print(soup.select('ul li'))
print(soup.select('#list-2 .element'))
print(type(soup.select('ul')[0]))
#获取属性
for ul in soup.select('ul'):
print(ul['id'])
print(ul.attrs['id'])
#获取内容
for li in soup.select('li'):
print(li.get_text()) '''
总结:
推荐使用lxml解析库,必要时使用html.parser
标签选择筛选功能弱但是速度快
建议使用find()、find_all()查询匹配单个结果或多个结果
如果对CSS选择器熟悉建议使用select()
记住常用的获取属性和文本值的方法
'''

BeautifulSoup库的更多相关文章

  1. Python爬虫小白入门(三)BeautifulSoup库

    # 一.前言 *** 上一篇演示了如何使用requests模块向网站发送http请求,获取到网页的HTML数据.这篇来演示如何使用BeautifulSoup模块来从HTML文本中提取我们想要的数据. ...

  2. BeautifulSoup库children(),descendants()方法的使用

    BeautifulSoup库children(),descendants()方法的使用 示例网站:http://www.pythonscraping.com/pages/page3.html 网站内容 ...

  3. 网络爬虫BeautifulSoup库的使用

    使用BeautifulSoup库提取HTML页面信息 #!/usr/bin/python3 import requests from bs4 import BeautifulSoup url='htt ...

  4. BeautifulSoup库的使用

    1.简介 BeautifulSoup库也是一个HTML/XML的解析器,其使用起来很简单,但是其实解析网站用xpath和re已经足矣,这个库其实很少用到.因为其占用内存资源还是比xpath更高. '' ...

  5. python爬虫学习之使用BeautifulSoup库爬取开奖网站信息-模块化

    实例需求:运用python语言爬取http://kaijiang.zhcw.com/zhcw/html/ssq/list_1.html这个开奖网站所有的信息,并且保存为txt文件和excel文件. 实 ...

  6. python下载安装BeautifulSoup库

    python下载安装BeautifulSoup库 1.下载https://www.crummy.com/software/BeautifulSoup/bs4/download/4.5/ 2.解压到解压 ...

  7. 基于BeautifulSoup库的HTML内容的查找

    一.BeautifulSoup库提供了一个检索的参数: <>.find_all(name,attrs,recursive,string,**kwargs),它返回一个列表类型,存储查找的结 ...

  8. python BeautifulSoup库的基本使用

    Beautiful Soup 是用Python写的一个HTML/XML的解析器,它可以很好的处理不规范标记并生成剖析树(parse tree). 它提供简单又常用的导航(navigating),搜索以 ...

  9. python爬虫学习(一):BeautifulSoup库基础及一般元素提取方法

    最近在看爬虫相关的东西,一方面是兴趣,另一方面也是借学习爬虫练习python的使用,推荐一个很好的入门教程:中国大学MOOC的<python网络爬虫与信息提取>,是由北京理工的副教授嵩天老 ...

随机推荐

  1. C# 函数1 (函数的定义)

    1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 na ...

  2. SqlServer 线下讲座

    2017年有幸在某互联网公司及其子公司进行了一次技术分享性质的讲座,讲座内容主要针对sqlserver 2017以及azure sql 的一些技术特性,进一步展示sql server 及其相关产品的新 ...

  3. Spring Boot 菜鸟教程 application.properties 常用配置

    SPRING CONFIG (ConfigFileApplicationListener) spring.config.name 配置文件名称,默认为application spring.config ...

  4. RPC入门总结(一)RPC定义和原理

    转载:深入浅出 RPC - 浅出篇 转载:RPC框架与Dubbo完整使用 转载:深入浅出 RPC - 深入篇 转载:远程调用服务(RPC)和消息队列(Message Queue)对比及其适用/不适用场 ...

  5. Jenkins+Ansible+Gitlab自动化部署三剑客-Jenkins本地搭建

    后面需要shell基础,目前没有,等有了,再更

  6. Android Call requires API level 19 (current min is 15)

    在 Android 应用开发时候,配置文件中声明了支持的Android系统范围: minSdkVersion 15targetSdkVersion 27 但是代码中需要使用的一个类 (android. ...

  7. Rancher2-----了解什么是rancher以及简单部署

    个人理解:就是相当于openstack的图形化界面,或者说应用程序的图形化界面,rancher功能就是在图形化界面去管理容器,包括运行容器,创建网络,存储等:rancher有个应用商店,可以根据自己的 ...

  8. Python之TabError: inconsistent use of tabs and spaces in indentation和ModuleNotFoundError:No module named 'win32api'

    1.TabError: inconsistent use of tabs and spaces in indentation 这是我的代码,感觉没啥不对, 后来运行之后出现了下面的错误,我也是弄了好久 ...

  9. SDOI2014 R1做题笔记

    SDOI2014 R1做题笔记 经过很久很久的时间,shzr又做完了SDOI2014一轮的题目. 但是我不想写做题笔记(

  10. python入门学习:4.if语句

    python入门学习:4.if语句 关键点:判断 4.1 一个简单的测试4.2 条件测试4.3 if语句 4.1 一个简单的测试   if语句基本格式如下,注意不要漏了冒号 1if 条件 :2     ...