BeautifulSoup库

<html>
<body>
<p class='title'></p>
</body>
</html>

BeautifulSoup库是解析、遍历、维护、"标签树"的功能库

对标签的理解

<p class='title'></p>
<!--成对的尖括号和属性-->

导入beautifulsoup库

from bs4 import BeautifulSoup
import bs4

构造解析html的BeautifulSoup对象

from bs4 import BeautifulSoup
soup1=BeautifulSoup("<html>data</html>","html.parser")
soup2=BeautifulSoup(open("D://demo.html"),"html.parser")

BeautifulSoup库对应一个HTML/XML文档的全部内容

四种解析器

解析器 使用方法 条件
bs4的HTML解析器 BeautifulSoup(mk,'html.parser') 安装bs4库
lxml的HTML解析器 BeautifulSoup(mk,'lxml') pip install lxml
lxml的xml解析器 BeautifulSoup(mk,'xml') pip install lxml
html5lib的解析器 BeautifulSoup(mk,'html5lib') pip install html5lib

五种基本元素

基本元素 说明
Tag 标签,<>开头和</>结尾
Name 标签的名字,格式.name
Attribute 标签的属性,字典形式进行组织,.attrs
NavigatableString 标签内非属性字符串,格式.string
Comment 标签内字符串注释部分

获取页面信息demo

from bs4 import BeautifulSoup
import requests
html=requests.get('http://python123.io/ws/demo.html').text
soup=Beautiful(demo,'html.parser')
tag=soup.a#获取第一个a标签
name=tag.name#'a',标签的名称
parentName=soup.a.parent.name#获取父亲节点的名称
attr=tag.attrs#属性值,字典
attr['class']#访问对应标签的属性
type(attr)#字典
tag.a.string#标签之间的信息
newsoup=BeautifulSoup('<b><!--This is a comment-->></b><p>
This is not a comment</p>','html.parser')
type(newsoup.b.string)#注释类型
type(newsoup.p.string)#文本类型

最新文章

  1. java 500/404错误总结
  2. Unity3D The Blacksmith Demo部分内容学习
  3. 【SET】ORACLE SET 命令
  4. .net 将excel转成html文件
  5. 快速打出System.out.println(&quot;&quot;);
  6. 解决VTune错误.../lib64/libstdc++.so.6: version `GLIBCXX_3.4.14&amp;#39; not found (required by ...)
  7. [Python]sqlite3二进制文件存储问题(BLOB)(You must not use 8-bit bytestrings unless you use a text_factory...)
  8. seajs +gruntjs 合作开发
  9. c语言判断打开文件是否为空的方法
  10. Hive DQL详解
  11. TCP的三次握手与四次挥手理解及面试题(很全面)
  12. emWin notes
  13. Java 8 forEach examples遍历例子
  14. iOS中self.xxx 和 _xxx 下划线的区别
  15. 转:ASP.NET MVC 将IList&lt;T&gt;导出Excel文档的泛型类
  16. 你会用AngularJS,但你会写AngularJS文档么?
  17. hdu 1253
  18. JS中的转义字符
  19. 使用jQuery操作DOM(2)
  20. Python迭代dict的value

热门文章

  1. redis集群搭建_超详细
  2. 【leetcode database】Human Traffic of Stadium
  3. TypeScript作为前端开发你必须学习的技能(三)
  4. 阿里云移动研发平台 EMAS 助力银行业打造测试中台,提升发版效能
  5. 图片转base64使用JSON传输
  6. linux 中统计目录/文件数量
  7. noip模拟题 Market
  8. sh_03_程序计数
  9. Atom 输入时按 Tab 快捷键提示怎么取消?
  10. Linux whatis命令失效 nothing appropriate