下文中soup均表示BeautifulSoup对象,tag均代指标签
1.引入第三方库:
from bs4 import BeautifulSoup
注意BeautifulSoup大小写
2.建立BeautifulSoup对象:
eg:soup=BeautifulSoup('字符串','lxml')
3.格式化打印(让爬取到的HTML内容更舒服的阅读):
soup.prettify()-------显示全部的格式化代码
soup.tag.prettify()----显示内容中第一个出现的该标签的内容
4.标签内容可通过 soup.tag查看
eg:soup.b---------查看b标签的内容
5.可通过 soup.find()查找第一个出现的该标签
6.可通过soup.find_all (name, attrs, recursive, string, **kwargs)查找所有该标签可加上属性名(几种参数选一种进行查找即可)
Name标签名查找 Eg :
soup.find_all('a’,’b’)-------找出所有a标签与b标签
正则表达式与find_all()的结合:
soup.find_all(re.compile(‘b’))--------找出所有以b开头的标签
attrs(属性查找)
recursive参数(bool型):是否对子孙全部检索,默认为True
string参数:<>…</>中字符串区域的检索字符串
7.tag 的属性:
(1)name-----获取标签的名字
(2)attrs----获取标签的属性
(3)string---tag中包含的字符串
8.部分词义解释:
NavigableString------Tag当中的字符串
comment--------------NavigableString的一个子类
对于结构简单的数据适合用beautifulsoup爬取,而对于结构复杂的数据则适合用‘正则表达式’爬取数据
9.HTML内容遍历:
-
(1)下行遍历:
<1>soup.tag.contents-------------返回儿子节点的列表,将该标签的所有子节点存入列表
eg: >>>soup.head.contents [<title>This is a python demo page</title>]
<2>soup.tag.children------------子节点的迭代类型,用于循环结构中遍历儿子节点
eg: >>> for child in soup.body.children: print(child)
<3>soup.tag.descendants---------子孙节点的迭代类型,用于循环结构中遍历所有子孙类型(注意是一个复合标签其中所有子节点全部遍历完后才去遍历另一个复合节点)
eg: >>> for child in soup.body.children: print(child)
-
(2)上行遍历:
<1> soup.tag.parent---------节点的父标签
<2> soup.tag.parents--------节点的先辈标签的迭代类型,用于遍历先辈节点 -
(3)平行遍历:
条件:发生在同一个父节点下的各节点间
使用注意:平行标签之间的字符串也作为节点对于下列一串爬取到的代码:
<html> <head> <title> This is a python demo page </title> </head> <body> <p class="title"> <b> The demo python introduces several python courses. </b> </p> <p class="course"> Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses: <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1"> Basic Python </a> and <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2"> Advanced Python </a> </p> </body> </html>
<1> soup.tag.next_sibling-------返回下一个平行节点标签,也可以连续使用
Eg1: >>>soup.a.next_sibling # a标签的下一个标签
' and '
Eg2: >>>soup.a.next_sibling.next_sibling
<a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>
<2> soup.tag.previous_sibling----返回上一个平行节点标签,可以连续使用
<3> soup.tag.next_siblings-------迭代类型,返回后续所有节点
<4> soup.tag.previous_siblings—迭代类型,返回前面的所有节点(注意是同一个父标签下的平行节点)