码迷,mamicode.com
首页 > 编程语言 > 详细

python BeautifulSoup库的基本使用

时间:2017-10-14 18:39:08      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:区域   地址   compile   install   print   python   com   html5   通过   

Beautiful Soup 是用Python写的一个HTML/XML的解析器,它可以很好的处理不规范标记并生成剖析树(parse tree)。 它提供简单又常用的导航(navigating),搜索以及修改剖析树的操作。它可以大大节省你的编程时间。

安装

1. 可以利用 pip 或者 easy_install 来安装,以下两种方法均可

easy_install beautifulsoup4

pip install beautifulsoup4

 2. 如果想安装最新的版本,请直接下载安装包来手动安装,也是十分方便的方法。

下载地址:https://pypi.python.org/pypi/beautifulsoup4/4.3.2

下载完成之后解压

运行下面的命令即可完成安装

sudo python setup.py install

 使用

中文文档

本文将以下面的HTML代码,讲解使用BeautifulSoup库,bs4库将任何HTML输入都变成utf‐8编码

>>> import requests
>>> r = requests.get(‘http://python123.io/ws/demo.html‘)
>>> r.text
‘<html><head><title>This is a python demo page</title></head>\r\n
<body>\r\n<p class="title"><b>The demo python introduces several python courses.</b>
</p>\r\n<p class="course">Python is a wonderful general-purpose programming language. 
You can learn Python from novice to professional by tracking the following courses:\r\n
<a href="http://www.icourse163.org/course/BIT-268001" class="py1" id="link1">Basic Python</a>
 and <a href="http://www.icourse163.org/course/BIT-1001870001" class="py2" id="link2">Advanced Python</a>
.</p>\r\n</body></html>‘
>>> demo = r.text

 1. BeautifulSoup4库的引用

from bs4 import BeautifulSoup

import bs4

 2. BeautifulSoup4库解析器

soup = BeautifulSoup(‘data‘,‘html.parser‘)
解析器 使用方法 条件
bs4的HTML解析器 BeautifulSoup(mk, ‘html.parser‘) 安装bs4库
lxml的HTML解析器 BeautifulSoup(mk, ‘lxml‘) 安装 lxml 库
lxml的XML解析器 BeautifulSoup(mk, ‘xml‘) 安装 lxml 库
html5lib的解析器 BeautifulSoup(mk, ‘html5lib‘) 安装 html5lib 库

 3. BeautifulSoup类的基本元素

 基本元素  说明
 Tag  标签,最基本的信息组织单元,分别用<>和</>标明开头和结尾
 Name  标签的名字,<p>...</p>的名字是‘p‘,格式:<tag>.name
 Attributes  标签的属性,字典形式组织,格式:<tag>.attrs
 NavigableString  标签内非属性字符串,<>...</>中字符串,格式:<tag>.string
 Comment  标签内字符串的注释部分,一种特殊的Comment类型
############## Tag标签 ##############
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(demo, ‘html.parser‘)
>>> soup.title
<title>This is a python demo page</title>
>>> tag = soup.a
>>> tag
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>

任何存在于HTML语法中的标签都可以用soup.<tag>访问获得,当HTML文档中存在多个相同<tag>对应内容时,soup.<tag>返回第一个

##############  Tag Name(名字) ##############
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(demo, ‘html.parser‘)
>>> soup.a.name
‘a‘
>>> soup.a.parent.name	#父级标签名称
‘p‘
>>> soup.a.parent.parent.name	##父级的父级的标签名称
‘body‘

每个<tag>都有自己的名字,通过<tag>.name获取,字符串类型

##############  Tag attrs(属性) ##############
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(demo, ‘html.parser‘)
>>> tag = soup.a
>>> tag.attrs
{‘class‘: [‘py1‘], ‘id‘: ‘link1‘, ‘href‘: ‘http://www.icourse163.org/course/BIT-268001‘}
>>> tag.attrs[‘class‘]
[‘py1‘]
>>> tag.attrs[‘href‘]
‘http://www.icourse163.org/course/BIT-268001‘
>>> type(tag.attrs)
<class ‘dict‘>
>>> type(tag)
<class ‘bs4.element.Tag‘>

一个<tag>可以有0或多个属性,字典类型

##############  Tag的NavigableString ##############
>>> soup.a
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>
>>> soup.a.string
‘Basic Python‘
>>> soup.title
<title>This is a python demo page</title>
>>> soup.title.string
‘This is a python demo page‘
>>> type(soup.title.string)
<class ‘bs4.element.NavigableString‘>

NavigableString可以跨越多个层次

##############  Tag的Comment ##############
>>> newsoup = BeautifulSoup(‘<b><!-- This is comment --></b><p>This is comment</p>‘, ‘html.parser‘)
>>> newsoup.b.string
‘ This is comment ‘
>>> type(newsoup.b.string)
<class ‘bs4.element.Comment‘>
>>> newsoup.p.string
‘This is comment‘
>>> type(newsoup.p.string)
<class ‘bs4.element.NavigableString‘>

Comment是一种特殊类型

 4. 标签树的遍历

BeautifulSoup类型是标签树的根节点

1)下行遍历

属性 说明
.contents 子节点的列表,将<tag>所有儿子节点存入列表
.children 子节点的迭代类型,与.contents类似,用于循环遍历儿子节点
.descendants 子孙节点的迭代类型,包含所有子孙节点,用于循环遍历
>>> soup.head
<head><title>This is a python demo page</title></head>
>>> soup.head.contents			#返回列表类型
[<title>This is a python demo page</title>]	
>>> soup.body.contents
[‘\n‘, <p class="title"><b>The demo python introduces several python courses.</b></p>, ‘\n‘, <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>, ‘\n‘]
>>> len(soup.body.contents)
5
>>> soup.body.contents[1]
<p class="title"><b>The demo python introduces several python courses.</b></p>

#遍历儿子节点
for child in soup.body.children:
    print(child)

#遍历子孙节点
for child in soup.body.descendants:
    print(child)

 2)上行遍历

属性 说明
 .parent  节点的父亲标签
 .parents  节点先辈标签的迭代类型,用于循环遍历先辈节点
>>> soup.title.parent
<head><title>This is a python demo page</title></head>
>>> soup.html.parent	#html的父节点是自己
<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	#没有父节点


#标签树的上行遍历(遍历所有先辈节点包括soup本身所以要区别判断)
for parent in soup.a.parents:
    if parent is None:
        print(parent)
    else:
        print(parent.name)

 3)平行遍历

 属性 说明
.next_sibling 返回按照HTML文本顺序的下一个平行节点标签
.previous_sibling 返回按照HTML文本顺序的上一个平行节点标签
.next_siblings 迭代类型,返回按照HTML文本顺序的后续所有平行节点标签
.previous_siblings 迭代类型,返回按照HTML文本顺序的前续所有平行节点标签
>>> soup.a.next_sibling
‘ and ‘
>>> soup.a.next_sibling.next_sibling
<a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>
>>> soup.a.previous_sibling
‘Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\r\n‘

#遍历后续节点
for sibling in soup.a.next_sibling:
	print(sibling)

#遍历前续节点
for sibling in soup.a.previous_sibling:
	print(sibling)

 5. 使用prettify方法更友好的输出

>>> import requests
>>> r = requests.get(‘http://python123.io/ws/demo.html‘)
>>> r.text
‘<html><head><title>This is a python demo page</title></head>\r\n<body>\r\n<p class="title"><b>The demo python introduces several python courses.</b></p>\r\n<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\r\n<a href="http://www.icourse163.org/course/BIT-268001" class="py1" id="link1">Basic Python</a> and <a href="http://www.icourse163.org/course/BIT-1001870001" class="py2" id="link2">Advanced Python</a>.</p>\r\n</body></html>‘
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(r.text, ‘html.parser‘)
>>> soup.prettify()
‘<html>\n <head>\n  <title>\n   This is a python demo page\n  </title>\n </head>\n <body>\n  <p class="title">\n   <b>\n    The demo python introduces several python courses.\n   </b>\n  </p>\n  <p class="course">\n   Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\n   <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">\n    Basic Python\n   </a>\n   and\n   <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">\n    Advanced Python\n   </a>\n   .\n  </p>\n </body>\n</html>‘
>>> print(soup.prettify())
<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>

 6. 内容查找

方法 说明
<>.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()参数

<>.find_all(name, attrs, recursive, string, **kwargs)

  • name : 对标签名称的检索字符串
  • attrs: 对标签属性值的检索字符串,可标注属性检索
  • recursive: 是否对子孙全部检索,默认True
  • string: <>…</>中字符串区域的检索字符串

<tag>(..) 等价于 <tag>.find_all(..)
soup(..) 等价于 soup.find_all(..)

#提取所有URL
for link in soup.find_all(‘a‘):
    print(link.get(‘href‘))
	
http://www.icourse163.org/course/BIT-268001
http://www.icourse163.org/course/BIT-1001870001

>>> soup.find_all(‘a‘)		#查找所有的a标签,返回一个列表
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]
>>> soup.find_all([‘a‘,‘b‘])	#查找所有的a标签和b标签,返回一个列表
[<b>The demo python introduces several python courses.</b>, <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]


>>> soup.find_all(‘p‘,‘course‘)		#查找所有具有course属性的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>]
>>> soup.find_all(id=‘link1‘)	#查找所有属性为id=‘link1‘的标签
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>]

>>> import re		#使用正则查找所有id属性中以‘link‘开头的标签
>>> soup.find_all(id=re.compile(‘link‘))
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]

>>> soup.find_all(‘a‘)
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]
>>> soup.find_all(‘a‘,recursive=False)	#查找所有a标签且不遍历子孙节点
[]

>>> soup.find_all(string="Basic Python")		#查找所有标签间内容为"Basic Python"的字符串
[‘Basic Python‘]
>>> import re
>>> soup.find_all(string=re.compile(‘python‘))
[‘This is a python demo page‘, ‘The demo python introduces several python courses.‘]	#查找所有标签间内容中有"python"的字符串

 

python BeautifulSoup库的基本使用

标签:区域   地址   compile   install   print   python   com   html5   通过   

原文地址:http://www.cnblogs.com/zhichaoma/p/7666376.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!