python爬虫经常使用库之bs4html
bs4全名BeautifulSoup,是编写python爬虫经常使用库之一,主要用来解析html标签。html5
1.安装python
pip install beautifulsoup4程序员
或python3.x
python -m pip install beautifulsoup4
bs4中最基础的使用是BeautifulSoup类的使用,注意大小写哦。python爬虫
用BeautifulSoup来解析html:编码
from bs4 import BeautifulSoup soup1 = BeautifulSoup("<html> A Html Text</html>", "html.parser") soup2 = BeautifulSoup(open("d://demo.html"), "html.parser")两个参数:第一个参数是要解析的html文本,第二个参数是使用那种解析器,对于HTML来说就是html.parser,这个是bs4自带的解析器。 还能够安装lxml库来解析HTML或者XML,安装html5lib来解析html5lib。
#lxml解析html(需pip install lxml) BeautifulSoup(html,'lxml') #lxml解析XML BeautifulSoup(xml,'xml') #html5lib解析(需安装: pip install html5lib) BeautifulSoup(html5,'html5lib')
BeautifulSoup基本元素有:spa
基本元素 | 说明 |
---|---|
Tag | 标签,基本信息组织单元,用<>和</>标明开头和结尾 |
Name | 标签的名字,<p>...</p>的名字就是’p',用法<>.name |
Attributes | 标签属性,字典形式,用法:<>.attrs['href'] |
NavigableString | 标签内非属性字符串,<p>这是非属性字符串</p>,用法:<>.string |
Comment | 标签内的注释部分<p>显示的内容<!-- comment就是这里啦--></p> |
任何存在于html语法中的标签均可以用soup.<tag>访问得到。code
当HTML文档中存在多个相同的tag时,soup.<tag>返回第一个xml
>>> soup2 = BeautifulSoup("<p class=\"title\"><b>The Contents of b in first p</b></p><p class=\"course\">The second p</p>","html.parser") >>> soup2.p <p class="title"><b>The Contents of b in first p</b></p>
每一个Tag都有本身的名字,经过<tag>.name获取,字符串类型
>>> soup2.p.name 'p'2.1.3 Tag的attrs(属性)
一个Tag能够有0个或多个属性,字典类型。
>>> soup2.p.attrs {'class': ['title']} >>> soup2.p.attrs['class'] ['title']
NavigableString能够跨越多个层次的标签。
>>> soup2.p <p class="title"><b>The Contents of b in first p</b></p> >>> soup2.p.string 'The Contents of b in first p' >>>
Comment是一种特殊类型
>>> soup3 = BeautifulSoup("<p>This is a NavigableString</p><b><!-- This is a Comment --></b>","html.parser") >>> soup3.p <p>This is a NavigableString</p> >>> soup3.b <b><!-- This is a Comment --></b> >>> soup3.p.string 'This is a NavigableString' >>> type(soup3.p.string) <class 'bs4.element.NavigableString'> >>> soup3.b <b><!-- This is a Comment --></b> >>> soup3.b.string ' This is a Comment ' >>> type(soup3.b.string) <class 'bs4.element.Comment'> >>>
<p class="title">....</p>p -> tag.name 'p'
class="title" -> tag.attrs (字典列表)
... -> NavigableString OR Comment
2.2 使用bs4遍历html内容
HTML是个树状结构,<>...</>构成了从属关系。对HTML的遍历,有下行遍历,上行遍历和平行遍历三种遍历途径或方法。
2.2.1 下行遍历
属性 | 说明 |
---|---|
.contents | 子节点的列表,将<tag>全部的儿子节点存入列表 |
.children | 子节点的迭代类型,与.contents相似,主要用于循环遍历子节点 |
.descendants | 子孙节点的迭代类型,包含全部子孙节点,用于循环遍历。 |
BeautifulSoup类型是标签树的根节点。
soup.head soup.head.contents soup.body.contents len(soup.body.contents) soup.body.contents[0]遍历子节点:
for child in soup.body.children: print(child)遍历全部子孙节点:
for child in soup.body.descendants: print(child)
属性 | 说明 |
.parent | 节点的父节点 |
.parents | 节点的先辈节点标签的迭代类型,用于循环遍历先辈节点。 |
>>> soup <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> >>> soup.title.parent <head><title>This is a python demo page</title></head> >>> soup.html.parent <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> >>> soup.parent >>>注意:<html>..</html>标签的父节点是其自身
而soup自己的父节点是空。
进行先辈节点遍历时,包括soup自身,实际使用时须要判断。
for parent in soup.a.parents: if parent is None: print(parent) else: print(parent.name)
2.2.3 平行遍历
属性 | 说明 |
.next_sibling | 返回按照HTML文本顺序的下一个平行节点标签 |
.previous_sibling | 返回按照HTML文本顺序的上一个平行节点标签 |
.next_siblings | 迭代类型,返回按照HTML文本顺序的后续全部平行节点标签 |
.previous_siblings | 迭代类型,返回按照HTML文本顺序的前续全部平行节点标签 |
soup.a.next_sibling soup.a.next_sibling.nextsibling soup.a.previous_sibling soup.a.parent
遍历后续节点:
for sibling in soup.a.next_siblings:
print(sibling)
for sibling in previous_siblings:
print(sibling)
3.1 prettify()方法
.prettify()为HTML文本<>及其内容增长‘\n'
.prettify()可用于标签,方法<tag>.prettify()
print(soup.a.prettify())
bs4库将任何HTML输入都变成utf-8编码,python3.x 默认支持编码是utf-8。完美匹配!
4.使用bs4进行HTML内容查找
使用bs4进行HTML内容解析查找,基本方法是使用<>.find_all()来进行
4.1 .find_all()的基本使用方法
基本格式:
<tag>.find_all(name, attrs, recursive, string, **kwargs)
其返回值为一个列表,存储查找的结果
参数:
name -> 对标签名称的检索字符串,能够是个字符串列表,表达“或”关系
soup.find_all('a') soup.find_all(['a','b']) soup.find_all(True)
soup.find_all('a', 'title') soup.find_all(id='link1') soup.find_all(attrs = {"class":"course"})
string -> <>...</>中的....的检索字符串
soup.find_all(string = 'This is a sample')
<tag>(...) <--> <tag>.find_all(...)
soup(...) <--> soup.find_all(...)
程序员果真都是懒人..........
4.2 扩展方法
方法 | 说明 |
---|---|
<>.find() | 搜索且只返回一个结果,同.find_all()参数 |
<>.find_parents() | 在先辈节点中搜索,返回列表类型,同.find_all()参数 |
<>.find_parent() | 在先辈节点中返回一个结果,同.find()参数 |
<>.find_next_siblings() | 在后续平行节点中搜索,返回列表类型,同find_all()参数 |
<>.find_next_sibling() | 在后续平行节点中搜索,返回一个结果,同find()参数 |
<>.find_previous_siblings() | 在前续平行节点中搜索,返回列表类型,同find_all()参数 |
<>.find_previous_sibling() | 在前续平行节点中搜索,返回一个结果,同find()参数 |