# -*- 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

解析库-beautifulsoup模块的更多相关文章

  1. 爬虫----爬虫解析库Beautifulsoup模块

    一:介绍 Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.Beautiful Soup会帮你 ...

  2. 【爬虫入门手记03】爬虫解析利器beautifulSoup模块的基本应用

    [爬虫入门手记03]爬虫解析利器beautifulSoup模块的基本应用 1.引言 网络爬虫最终的目的就是过滤选取网络信息,因此最重要的就是解析器了,其性能的优劣直接决定这网络爬虫的速度和效率.Bea ...

  3. 【网络爬虫入门03】爬虫解析利器beautifulSoup模块的基本应用

    [网络爬虫入门03]爬虫解析利器beautifulSoup模块的基本应用   1.引言 网络爬虫最终的目的就是过滤选取网络信息,因此最重要的就是解析器了,其性能的优劣直接决定这网络爬虫的速度和效率.B ...

  4. 爬虫解析库——BeautifulSoup

    解析库就是在爬虫时自己制定一个规则,帮助我们抓取想要的内容时用的.常用的解析库有re模块的正则.beautifulsoup.pyquery等等.正则完全可以帮我们匹配到我们想要住区的内容,但正则比较麻 ...

  5. 爬虫解析库beautifulsoup

    一.介绍 Beautiful Soup是一个可以从HTML或XML文件中提取数据的python库. #安装Beautiful Soup pip install beautifulsoup4 #安装解析 ...

  6. 解析库beautifulsoup

    目录 一.介绍 二.遍历文档树 三.搜索文档树(过滤) 四.修改文档树 五.总结 一.介绍 Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的 ...

  7. 爬虫解析库BeautifulSoup的一些笔记

    BeautifulSoup类使用   基本元素 说明 Tag 标签,最基本的信息组织单元,分别是<>和</>标明开头和结尾 Name 标签的名字,<p></p ...

  8. 爬虫之解析库BeautifulSoup

    介绍 Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据.官方解释如下: Beautiful Soup提供一些简单的.python式的函数用来处理导航.搜索.修改分析树等 ...

  9. BeautifulSoup解析库

    解析库 解析器 使用方法 优势 劣势 Python标准库 BeautifulSoup(html, 'html.parser') 速度适中,容错能力强 老版本python容错能力差 lxml HTML解 ...

随机推荐

  1. ZKWeb网页框架2.0正式发布

    2.0.0更新的内容有 更新框架要求 框架要求从 netstandard 1.6 升到 netstandard 2.0 框架要求从 netcoreapp1.1 升到 netcoreapp2.0 更新引 ...

  2. javascript-发布订阅模式

    说明:本篇文章转载自小火柴的蓝色理想的一篇博文.原文地址:http://www.cnblogs.com/xiaohuochai/p/8031564.html 发布-订阅模式又叫观察者模式,它定义对象间 ...

  3. Centos7安装配置Xhgui

    XhProf是Facebook出品的一个PHP性能监控工具,只包含基本的界面和图形来分析数据.后来Paul Reinheimer在此基础上开发了Xhgui,提供了更好的界面和功能,其主页在https: ...

  4. python爬虫小结1

    先看正则化,正则化就是描述命令和字符切分.查找.筛选等功能的方便方式. http://www.cnblogs.com/fnng/archive/2013/05/20/3089816.html 一个游戏 ...

  5. EclipseIDE设置

    对于新安装的Eclipse而言要设置: 1.Window-Preferences-General-Workspace,然后分别设置Text file encoding为UTF-8和设置New text ...

  6. zepto的返回顶部scrollTop的动画解决方法

    写移动端的时候,引入的zepto.js里的animate不包括scrollTop,所以返回顶部的时候,没有动画的效果.这里我使用的是setInterval的方法.代码详情如下 <!DOCTYPE ...

  7. JMeter集合点

    位置:添加--> 定时器-->Synchronizing Timer     注意:集合点放在所有操作之前.   假设线程组线程数设置的是50个,那么希望50个都准备好一块上,那么集合点中 ...

  8. POI 导出导入工具类介绍

    介绍: Apache POI是Apache软件基金会的开源项目,POI提供API给Java程序对Microsoft Office格式档案读和写的功能. .NET的开发人员则可以利用NPOI (POI ...

  9. leetcode — reorder-list

    /** * Source : https://oj.leetcode.com/problems/reorder-list/ * * Given a singly linked list L: L0→L ...

  10. c3p0使用记录

    首先要导入c3p0包.c3p0下载解压后,lib目录下有三个包,使用mysql的话,只需要导入c3p0-0.9.5.2.jar,mchange-commons-java-0.2.11.jar. 要连接 ...