解析库-beautifulsoup模块

# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup

# 安装:pip install beautifulsoup4
# Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,其中一个是 lxml .根据操作系统不同,可以选择下列方法来安装lxml:
# 安装解析器:pip install lxml
# 另一个可供选择的解析器是纯Python实现的 html5lib , html5lib的解析方式与浏览器相同,可以选择下列方法来安装html5lib:
# 安装解析器:pip install html5lib


# 基本使用:直接连接网页太麻烦,直接拿下载好的网页做测试;

# html_doc = """
# <html><head><title>The Dormouse's story</title></head>
# <body>
# <p class="title"><b>The Dormouse's story</b></p>
# <p class="title"><b>The Dormouse's story2</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>
# """

# 基本使用:容错处理,文档的容错能力指的是在HTML代码不完整的情况下,使用该模块可以识别错误
# 使用该Beautifulsoup解析上述代码,能够得到一个bearutifulsoup对象,并且按照标准格式输出
# soup = BeautifulSoup(html_doc,"lxml")    # 具有容错功能
# print(soup.prettify())     #可以处理好缩进,按照标准格式输出
# soup = BeautifulSoup(html_doc,"html.parser")
# print(soup)

# 遍历文档树
# 1、用法
# soup = BeautifulSoup(open("a.html"),"lxml")
# soup = BeautifulSoup(html_doc,"lxml")
# print(soup.p)       #存在多个相同的标签只返回第一个
# print(soup.a)
# 2、获取标签的名称
# print(soup.p.name)           #获取该标签的名称,不过有点多此一举
# 3、获取标签属性
# print(soup.p.attrs)
# 4、获取标签的内容
# print(soup.p.string)      # p下边没有子元素的时候返回他的文本,否则返回none
# print(soup.p.strings)       # 拿到p的生成器对象
# print(soup.p.text)            #去文本内容
# for line in soup.stripped_strings:
#     print(line)                 # 去掉空白,打印p的文本内容
# 5、嵌套选择:
# print(soup.head.title.string)      #标签嵌套
# print(soup.body.a.string)
# 6、子节点,子孙接点
# print(soup.p.contents)       #取p下边的所有子节点
# print(soup.p.children)         #得到一个迭代器,包含p下的所有子节点
# for i in soup.p.children:
#     print(i)
# for i,child in enumerate(soup.p.children):
#     print(i,child)
# print(soup.p.descendants)
# for i,child in enumerate(soup.p.descendants):
#     print(i,child)        # 获取子孙接点
# 7、父节点,祖先接点
# print(soup.a.parent)          #获取a的父节点
# print(list(soup.a.parents))     #获取到a的所有祖先元素、
# 8、兄弟接点
# print(soup.a.next_sibling)     #h获取a的上一个兄弟
# print(soup.a.previous_sibling)   # h获取a的下一个兄弟

# print(list(soup.a.next_siblings))    #所有的兄弟列表
# print(soup.a.previous_siblings)     #兄弟的生成器对象

# 搜索文档树
# 五种过滤器: 字符串、正则表达式、列表、True、方法

    # 1、字符串:标签名
    # print(soup.find_all("b"))
    # 2、正则表达式
    # import re
    # print(soup.find_all(re.compile("^b")))
    # 3、列表
    # print(soup.find_all(["a","b"]))     # 找到a或b
    # 4、True
    # print(soup.find_all(True))     #找到所有的tag
    # for tag in soup.find_all(True):
    #     print(tag.name)           #找到所有的标签名
    # 5、方法:如果没有合适过滤器,那么还可以定义一个方法,方法只接受一个元素参数 ,如果这个方法返回 True 表示当前元素匹配并且被找到,如果不是则反回 False
    # def has_class_but_no_id(tag):
    #     return tag.has_attr("class") and not tag.has_attr("id")
    #
    # print(soup.find_all(has_class_but_no_id))
# find_all( name , attrs , recursive , text , **kwargs )
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p id="my p" class="title"><b id="bbb" class="boldest">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>
"""
import re
from bs4 import BeautifulSoup
soup=BeautifulSoup(html_doc,'lxml')

# 1、name: 搜索name参数的值可以使任一类型的 过滤器 ,字符窜,正则表达式,列表,方法或是 True
# print(soup.find_all(name=re.compile("^t")))
# 2、keyword: key=value的形式,value可以是过滤器:字符串 , 正则表达式 , 列表, True .
# print(soup.find_all(id=re.compile("my")))
# print(soup.find_all(href=re.compile("lacie"),id=re.compile("\d")))
# print(soup.find_all(id=True))?
# # 有些tag属性在搜索不能使用,比如HTML5中的 data-* 属性:
# data_soup = BeautifulSoup('<div data-foo="value">foo!</div>','lxml')
# # data_soup.find_all(data-foo="value") #报错:SyntaxError: keyword can't be an expression
# # 但是可以通过 find_all() 方法的 attrs 参数定义一个字典参数来搜索包含特殊属性的tag:
# print(data_soup.find_all(attrs={"data-foo": "value"}))
# # [<div data-foo="value">foo!</div>]
# 3、按照类名查找,注意关键字是class_,class_=value,value可以是五种选择器之一
# print(soup.find_all('a',class_='sister')) #查找类为sister的a标签
# print(soup.find_all('a',class_='sister ssss')) #查找类为sister和sss的a标签,顺序错误也匹配不成功
# print(soup.find_all(class_=re.compile('^sis'))) #查找类为sister的所有标签
# 4、attrs
# print(soup.find_all("p",attrs={"class":"story"}))
# 5、text: 值可以是:字符,列表,True,正则
# print(soup.find_all(text='Elsie'))
# print(soup.find_all('a',text='Elsie'))
# 6、limit参数:如果文档树很大那么搜索会很慢.如果我们不需要全部结果,可以使用 limit 参数限制返回结果的数量.效果与SQL中的limit关键字类似,当搜索到的结果数量达到 limit 的限制时,就停止搜索返回结果??
# print(soup.find_all("a",limit=2))
# 7、recursive:调用tag的 find_all() 方法时,Beautiful Soup会检索当前tag的所有子孙节点,如果只想搜索tag的直接子节点,可以使用参数 recursive=False .
# print(soup.html.find_all("a"))
# print(soup.find_all("a"))
# print(soup.html.find_all("a",recursive=False))



# find( name , attrs , recursive , text , **kwargs )   # 和find_all类似

# html_doc = """
# <html><head><title>The Dormouse's story</title></head>
# <body>
# <p class="title">
#     <b>The Dormouse's story</b>
#     Once upon a time there were three little sisters; and their names were
#     <a href="http://example.com/elsie" class="sister" id="link1">
#         <span>Elsie</span>
#     </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>;
#     <div class='panel-1'>
#         <ul class='list' id='list-1'>
#             <li class='element'>Foo</li>
#             <li class='element'>Bar</li>
#             <li class='element'>Jay</li>
#         </ul>
#         <ul class='list list-small' id='list-2'>
#             <li class='element'><h1 class='yyyy'>Foo</h1></li>
#             <li class='element xxx'>Bar</li>
#             <li class='element'>Jay</li>
#         </ul>
#     </div>
#     and they lived at the bottom of a well.
# </p>
# <p class="story">...</p>
# """
# from bs4 import BeautifulSoup
# soup=BeautifulSoup(html_doc,'lxml')


# css选择器
# 1、css选择器
# print(soup.select(".sister span"))

# print(soup.select("#link1"))
# print(soup.select("#link1 span"))

# print(soup.select("#list-2 .element.xxx"))
# print(soup.select("#list-2")[0].select(".element"))
# 2、获取属性
# print(soup.select("#list-2 h1")[0].attrs)

# 3、获取内容
# print(soup.select("#list-2 h1")[0].get_text())
import requests
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="title"><b>The Dormouse's story2</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>
"""
soup = BeautifulSoup(html_doc,"lxml")
# print(soup)     #完整的HTML文档
# print(soup.text)   #所有网页的文本信息
# print(soup.p.attrs)     #获取到第一个p的属性值
# print(soup.find_all("p"))    #获取到所有的p标签的标签信息
p_s = soup.find_all("p")
# for p in p_s:       #循环每一个p标签
#     print(p.text)    #打印每个p标签的文本信息
# for p in p_s:
    # print(p.a)          #打印p下边的a标签
# a_l = soup.find("a")
# print(a_l.get("href"))      #获取到a标签的href属性

# a_s = soup.find_all("a",attrs={"class":"sister"})    #找到所有具有sister属性的a标签
# print(a_s)

# a_t = soup.find_all("a",text="Elsie")            #获取到a标签的文本是elsie的标签
# print(a_t)


# a_ls = soup.find_all("a")
# for a in a_ls:
#     print(a.get("href"))

# select_a = soup.select("#link1")[0]
# print(select_a)
测试代码

 

修改文档树:中文链接 

https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html#id40

posted @ 2018-01-19 13:54  一石数字欠我15w!!!  阅读(370)  评论(0编辑  收藏  举报