beautifulSoap
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="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc)
print(soup.prettify())#以标准格式输出相应HTML
soup.p
soup.p['class']
soup.find_all('p')
soup.find(id="link3")
soup.find(class='a') 因为class是python关键字,正确语法应该是
soup.find('',{'class':'a'})
soup.get_text()从文档中获取所有文字内容:
Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种: Tag , NavigableString , BeautifulSoup , Comment .
BeautifulSoup->Tag->NavigableString
字符串常被包含在tag内.Beautiful Soup用 NavigableString 类来包装tag中的字符串:
BeautifulSoup 对象表示的是一个文档的全部内容.大部分时候,可以把它当作 Tag 对象,它支持 遍历文档树 和 搜索文档树 中描述的大部分的方法.
Comment (注释)对象是一个特殊类型的 NavigableString 对象:
一个Tag可能包含多个字符串或其它的Tag,这些都是这个Tag的子节点,Beautiful Soup提供了许多操作和遍历子节点的属性.。Beautiful Soup中字符串节点不支持这些属性,因为字符串没有子节点
tag的 .contents 属性可以将tag的子节点以列表的方式输出
tag的 .children 生成器,可以对tag的子节点进行循环:
.descendants 属性可以对所有tag的子孙节点进行递归循环
如果tag包含了多个子节点,tag就无法确定 .string 方法应该调用哪个子节点的内容
输出的字符串中可能包含了很多空格或空行,使用 .stripped_strings 可以去除多余空白内容:
通过 .parent 属性来获取某个元素的父节点.。通过元素的 .parents 属性可以递归得到元素的所有父辈节点
在文档树中,使用 .next_sibling 和 .previous_sibling 属性来查询兄弟节点:。通过 .next_siblings 和 .previous_siblings 属性可以对当前节点的兄弟节点迭代输出
搜索文档树
主要是find和find_all方法
字符串
最简单的过滤器是字符串.在搜索方法中传入一个字符串参数,Beautiful Soup会查找与字符串完整匹配的内容
soup.find_all('a')
正则表达式
如果传入正则表达式作为参数,Beautiful Soup会通过正则表达式的 match() 来匹配内容
找出所有以b开头的标签,这表示和标签都应该被找到
import re
for tag in soup.find_all(re.compile("^b")):
print(tag.name)
如果传入列表参数,Beautiful Soup会将与列表中任一元素匹配的内容返回
soup.find_all(["a", "b"])
True 可以匹配任何值,下面代码查找到所有的tag,但是不会返回字符串节点
for tag in soup.find_all(True):
如果没有合适过滤器,那么还可以定义一个方法,方法只接受一个元素参数
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)
...
修改文档树
使用Beautiful Soup解析后,文档都被转换成了Unicode:

浙公网安备 33010602011771号