咱们知道,Python拥有出色的内置HTML解析器模块——HTMLParser,然而还有一个功能更为强大的HTML或XML解析工具——BeautifulSoup(美味的汤),它是一个第三方库。简单来讲,BeautifulSoup最主要的功能是从网页抓取数据。本文咱们来感觉一下BeautifulSoup的优雅而强大的功能吧!html
BeautifulSoup3 目前已经中止开发,推荐在如今的项目中使用BeautifulSoup4,不过它已经被移植到bs4了,也就是说导入时咱们须要 import bs4 。能够利用 pip 或者 easy_install 两种方法来安装。下面采用pip安装。node
pip install beautifulsoup4python
pip install lxml
正则表达式
建议同时安装"lxml"模块,BeautifulSoup支持Python标准库中的HTML解析器(HTMLParser),还支持一些第三方的解析器,若是咱们不安装它,则 Python 会使用 Python默认的解析器,lxml 解析器更增强大,速度更快,推荐安装。express
安装后,建立对象:soup = BeautifulSoup(markup='html文件', 'lxml')函数
格式化输出:soup.prettify()工具
BeautifulSoup将复杂HTML文档转换成一个复杂的树形结构,每一个节点都是Python对象,全部对象能够概括为4种:spa
BeautifulSoup对象表示的是一个文档的所有内容:code
print soup.name
# [document]
即HTML的整个标签,如获取<title>标签:orm
print soup.title #<title>The Dormouse's story</title>
Tag有两个重要属性:name,attrs。
即HTML的标签名称:
print soup.name #[document] print soup.head.name #head
即HTML的标签属性字典:
print soup.p.attrs #{'class': ['title'], 'name': 'dromouse'}
若是想要单独获取某个属性:
print soup.p['class'] #['title']
既然咱们已经获得了整个标签,那么问题来了,咱们要想获取标签内部的文字内容怎么办呢?很简单,用 string 便可:
print soup.p.string #The Dormouse's story
HTML的注释内容,注意的是,不包含注释符号。咱们首先判断它的类型,是否为 Comment 类型,而后再进行其余操做,如打印输出:
if type(soup.a.string)==bs4.element.Comment: print soup.a.string #<!-- Elsie -->
获取全部子节点,返回列表:
print soup.head.contents #[<title>The Dormouse's story</title>]
获取全部子节点,返回列表生成器:
print soup.head.children #<listiterator object at 0x7f71457f5710> ## 须要遍历 for child in soup.body.children: print child ## 结果 <p class="title" name="dromouse"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p>
返回单个文本内容。若是一个标签里面没有标签了,那么 string 就会返回标签里面的内容。若是标签里面只有惟一的一个标签了,那么 string 也会返回最里面的内容。若是tag包含了多个子节点,tag就没法肯定,string 方法应该调用哪一个子节点的内容,string 的输出结果是 None。例如:
print soup.head.string print soup.title.string #The Dormouse's story #The Dormouse's story
print soup.html.string
# None
返回多个文本内容,且包含空行和空格。
返回多个文本内容,且不包含空行和空格:
for string in soup.stripped_strings: print(repr(string)) # u"The Dormouse's story" # u"The Dormouse's story" # u'Once upon a time there were three little sisters; and their names were' # u'Elsie' # u',' # u'Lacie' # u'and' # u'Tillie' # u';\nand they lived at the bottom of a well.' # u'...'
返回当前节点和子节点的文本内容。
from bs4 import BeautifulSoup html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister1" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister2" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister3" id="link3">Tillie</a>; and they lived at the bottom of a well. </p> <p class="story">...</p> </body> </html> """ soup = BeautifulSoup(markup=html_doc,features='lxml') node_p_text=soup.find('p',class_='story').get_text() # 注意class_带下划线 print(node_p_text) # 结果 Once upon a time there were three little sisters; and their names were Elsie, Lacie and Tillie; and they lived at the bottom of a well.
返回某节点的直接父节点:
p = soup.p print p.parent.name #body
返回某节点的全部父辈及以上辈的节点:
content = soup.head.title.string for parent in content.parents: print parent.name ## 结果 title head html [document]
next_sibling 属性获取该节点的下一个兄弟节点,结果一般是字符串或空白,由于空白或者换行也能够被视做一个节点。
previous_sibling 属性获取该节点的上一个兄弟节点。
print soup.p.next_sibling # 实际该处为空白 print soup.p.prev_sibling #None 没有前一个兄弟节点,返回 None print soup.p.next_sibling.next_sibling #<p class="story">Once upon a time there were three little sisters; and their names were #<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, #<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and #<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>; #and they lived at the bottom of a well.</p> #下一个节点的下一个兄弟节点是咱们能够看到的节点
迭代获取所有兄弟节点。
不是针对于兄弟节点,而是在于全部节点,不分层次的前一个和后一个节点。
迭代获取全部前和后节点。
find_all()方法搜索当前tag的全部tag子节点,并判断是否符合过滤器的条件。
name参数很强大,能够传多种方式的参数,查找全部名字为 name 的tag,字符串对象会被自动忽略掉。
(a)传标签名
最简单的过滤器是标签名。在搜索方法中传入一个标签名参数,BeautifulSoup会查找与标签名完整匹配的内容,下面的例子用于查找文档中全部的<a>标签:
print soup.find_all('a') #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
返回结果列表中的元素仍然是BeautifulSoup对象。
(b)传正则表达式
若是传入正则表达式做为参数,BeautifulSoup会经过正则表达式的 match() 来匹配内容。下面例子中找出全部以b开头的标签,这表示<body>和<b>标签都应该被找到:
import re for tag in soup.find_all(re.compile("^b")): print(tag.name) # body # b
(c)传列表
若是传入列表参数,BeautifulSoup会将与列表中任一元素匹配的内容返回。下面代码找到文档中全部<a>标签和<b>标签:
soup.find_all(["a", "b"]) # [<b>The Dormouse's story</b>, # <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, # <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, # <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
(d)传True
True 能够匹配任何值,下面代码查找到全部的tag,可是不会返回字符串节点:
for tag in soup.find_all(True): print(tag.name) # html # head # title # body # p # b # p # a # a
(e)传函数
若是没有合适过滤器,那么还能够定义一个方法,方法只接受一个元素参数。若是这个方法返回 True 表示当前元素匹配而且被找到,若是不是则反回 False:
def has_class_but_no_id(tag): return tag.has_attr('class') and not tag.has_attr('id') soup.find_all(has_class_but_no_id) # [<p class="title"><b>The Dormouse's story</b></p>, # <p class="story">Once upon a time there were...</p>, # <p class="story">...</p>]
注意的是,若是一个指定名字的参数不是搜索内置的参数名,搜索时会把该参数看成指定名字tag的属性来搜索,若是包含一个名字为 id 的参数,BeautifulSoup会搜索每一个tag的”id”属性:
soup.find_all(id='link2') # [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
若是传入 href 参数,Beautiful Soup会搜索每一个tag的"href"属性:
soup.find_all(href=re.compile("elsie")) # [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
使用多个指定名字的参数能够同时过滤tag的多个属性:
soup.find_all(href=re.compile("elsie"), id='link1') # [<a class="sister" href="http://example.com/elsie" id="link1">three</a>]
在这里咱们想用 class 过滤,不过 class 是 python 的关键词,这怎么办?加个下划线就能够:
soup.find_all("a", class_="sister") # [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, # <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, # <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
有些tag属性在搜索不能使用,好比HTML5中的 " data-* " 自定义属性:
data_soup = BeautifulSoup('<div data-foo="value">foo!</div>') data_soup.find_all(data-foo="value") # SyntaxError: keyword can't be an expression ## 可是能够经过 find_all() 方法的 attrs 参数定义一个字典参数来搜索包含特殊属性的tag data_soup.find_all(attrs={"data-foo": "value"}) # [<div data-foo="value">foo!</div>]
经过 text 参数能够搜搜文档中的字符串内容。与 name 参数的可选值同样,text 参数接受字符串 、正则表达式 、列表、True。
soup.find_all(text="Elsie") # [u'Elsie'] soup.find_all(text=["Tillie", "Elsie", "Lacie"]) # [u'Elsie', u'Lacie', u'Tillie'] soup.find_all(text=re.compile("Dormouse")) # 模糊查找 [u"The Dormouse's story", u"The Dormouse's story"]
find_all() 方法返回所有的搜索结构,若是文档树很大那么搜索会很慢。若是咱们不须要所有结果,可使用 limit 参数限制返回结果的数量。效果与SQL中的limit关键字相似,当搜索到的结果数量达到 limit 的限制时,就中止搜索返回结果。
soup.find_all("a", limit=2) # [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, # <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
调用tag的 find_all() 方法时,BeautifulSoup会检索当前tag的全部子孙节点,若是只想搜索tag的直接子节点,可使用参数 recursive=False。
soup.html.find_all("title") # [<title>The Dormouse's story</title>] soup.html.find_all("title", recursive=False) # []
它与 find_all() 方法惟一的区别是 find_all() 方法的返回结果是值包含一个元素的列表,而 find() 方法直接返回结果。
find_all() 和 find() 只搜索当前节点的全部子节点,孙子节点等。find_parents() 和 find_parent() 用来搜索当前节点的父辈节点,搜索方法与普通tag的搜索方法相同,搜索文档搜索文档包含的内容。
这2个方法经过 .next_siblings 属性对当 tag 的全部后面解析的兄弟 tag 节点进行迭代, find_next_siblings() 方法返回全部符合条件的后面的兄弟节点,find_next_sibling() 只返回符合条件的后面的第一个tag节点。
这2个方法经过 .previous_siblings 属性对当前 tag 的前面解析的兄弟 tag 节点进行迭代, find_previous_siblings() 方法返回全部符合条件的前面的兄弟节点,find_previous_sibling() 方法返回第一个符合条件的前面的兄弟节点。
这2个方法经过 .next_elements 属性对当前 tag 的以后的 tag 和字符串进行迭代, find_all_next() 方法返回全部符合条件的节点, find_next() 方法返回第一个符合条件的节点。
这2个方法经过 .previous_elements 属性对当前节点前面的 tag 和字符串进行迭代,find_all_previous() 方法返回全部符合条件的节点, find_previous()方法返回第一个符合条件的节点。
咱们在写 CSS 时,标签名不加任何修饰,类名前加点,id名前加 #,在这里咱们也能够利用相似的方法来筛选元素,用到的方法是 soup.select(),返回类型是 list。
print soup.select('title') #[<title>The Dormouse's story</title>] print soup.select('a') #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>] print soup.select('b') #[<b>The Dormouse's story</b>]
print soup.select('.sister') #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
print soup.select('#link1') #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
组合查找即和写 class 文件时,标签名与类名、id名进行的组合原理是同样的,例如查找 p 标签中,id 等于 link1的内容,两者须要用空格分开。
print soup.select('p #link1') #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
直接子标签查找:
print soup.select("head > title") #[<title>The Dormouse's story</title>]
查找时还能够加入属性元素,属性须要用中括号括起来,注意属性和标签属于同一节点,因此中间不能加空格,不然会没法匹配到。
print soup.select('a[class="sister"]') #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>] print soup.select('a[href="http://example.com/elsie"]') #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
一样,属性仍然能够与上述查找方式组合,不在同一节点的空格隔开,同一节点的不加空格:
print soup.select('p a[href="http://example.com/elsie"]') #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
以上的 select 方法返回的结果都是列表形式,能够遍历形式输出,而后用 string或get_text() 方法来获取它的内容:
soup = BeautifulSoup(html, 'lxml') print type(soup.select('title')) print soup.select('title')[0].get_text() for title in soup.select('title'): print title.get_text()
至此,转载请注明出处。