环境为:

  • Python3.6
  • windows
  • pycharm2017.2.4

安装:

# 安装beautifulsoup4
  pip install beautifulsoup4# 安装解析器
  pip install lxml# 另一个可供选择的解析器是纯Python实现的 html5lib,html5lib的解析方式与浏览器相同pip install html5lib


基本使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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>
"""
#基本使用:容错处理,文档的容错能力指的是在html代码不完整的情况下,使用该模块可以识别该错误。<br>#使用BeautifulSoup解析上述代码,能够得到一个 BeautifulSoup 的对象,并能按照标准的缩进格式的结构输出
from bs4 import BeautifulSoup
soup=BeautifulSoup(html_doc,'lxml'#具有容错功能
res=soup.prettify() #处理好缩进,结构化显示
print(res)

标签选择器

1
即直接通过标签名字选择,选择速度快,如果存在多个相同的标签则只返回第一个<br><br>

from bs4 import BeautifulSouphtml_doc = """
<html><head><title>The Dormouse's story</title></head>
<body><p>first tag</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<i>this i tag</i></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.head) # <head><title>The Dormouse's story</title></head># 获取标签的属性
# print(soup.p.name) # p# 直接获取标签,如果存在多个相同的标签则只返回第一个
# print(soup.p) # <p>first tag</p># 获取标签的内容,# print(soup.p.string) # first tag
# print(soup.a.string) # None
# print(soup.p.text) # first tag
# print(soup.a.text) # Elsiethis i tag
# print(soup.a.contents) # ['Elsie', <i>this i tag</i>]
"""
注意
contents获取选中标签内的所有的值,包括里面的标签
string 只能获取当前标签,而无法获取子标签的内容,如果存在子标签,则返回None
text则获取包括子标签在内的所有值
"""# 嵌套选择
# print(soup.head.title.string) # The Dormouse's story
# print(soup.body.a.contents) # ['Elsie', <i>this i tag</i>]
# print(soup.body.a.text) # Elsiethis i tag
# print(soup.body.a.string) # None
# print(soup.body.p.string) # first tag# 获取子节点,子孙节点
# print(soup.contents) # 返回整个HTML页面的所有节点
# print(soup.p.contents) # ['first tag']
# print(soup.p.children) # 得到一个迭代器,包含此标签内错有的子节点
# print(list(soup.a.children)) # ['Elsie', <i>this i tag</i>]
# print(soup.p.descendants) # <generator object descendants at 0x00000162FFB9D570>
# print(list(soup.a.descendants)) # 获取子孙节点,p下所有的标签都会选择出来 ['Elsie', <i>this i tag</i>, 'this i tag']
# for i, child in enumerate(soup.p.descendants):
# print(i, child) # 0 first tag# 获取父节点,祖先节点
# print(soup.a.parent) # 获取 a 标签
# print(soup.a.parents) # <generator object parents at 0x0000022F8747D570>
# print(list(soup.a.parents)) # a 标签的父,父,父节点都会找出来,到html节点# 获取兄弟节点
# print(soup.a.next_siblings) # 生成器对象 <generator object next_siblings at 0x000002418B9BD570>
# print(list(soup.a.next_siblings))

beautifulsoup4标签选择器

View Code

标准选择器

from bs4 import BeautifulSouphtml_doc = """
<html><head><title>The Dormouse's story</title></head>
<body><p>first tag</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<i id="i1" class="i1">this i tag</i></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.find_all('a'))  # 拿到所有的标签
# print(soup.find_all('a', id='link2'))  # [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
# print(soup.find(id='link2'))  # <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
# print(soup.find_all(attrs={"class": "sister"}))  # 拿到所有的类为sister的a标签
# print(soup.find_all(class_='sister'))   # 拿到的结果也是所有的类名为sister的a标签
# 注意:soup.find_all(class_='sister' 中的class_ 的用法,要加下划线,因为class为关键字,写在attrs里面的没影响# 嵌套查找
# print(soup.find_all('a')[0].find('i'))  # 拿到 a 标签的下级 i 标签 <i>this i tag</i># 按照属性查找
# print(soup.a.find_all(attrs={'id':'i1'}))  # [<i class="i1" id="i1">this i tag</i>]
# print(soup.a.find_all(attrs={"class":'i1'})) # [<i class="i1" id="i1">this i tag</i>]
# print(soup.find_all(id='i1'))  # [<i class="i1" id="i1">this i tag</i>]# 按照文本内容查找,按照完全匹配来匹配内容,不是模糊的匹配,是== 不是 in
# print(soup.p.find_all(text='first tag'))  # ['first tag']

beautifulsoup4标准选择器

View Code

CSS选择器

##该模块提供了select方法来支持css
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')#1、CSS选择器
print(soup.p.select('.sister'))
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')) #可以一直select,但其实没必要,一条select就可以了# 2、获取属性
print(soup.select('#list-2 h1')[0].attrs)# 3、获取内容
print(soup.select('#list-2 h1')[0].get_text())CSS选择器

View Code

beautifulsoup4中文文档

转载于:https://www.cnblogs.com/q240756200/p/10671952.html

beautifulsoup4相关推荐

  1. CSS 选择器:BeautifulSoup4解析器

    和 lxml 一样,Beautiful Soup 也是一个HTML/XML的解析器,主要的功能也是如何解析和提取 HTML/XML 数据. lxml 只会局部遍历,而Beautiful Soup 是基 ...

  2. from beautifulsoup4 import BeautifulSoup 报错

    >>> from beautifulsoup4 import BeautifulSoup Traceback (most recent call last):   File &quo ...

  3. requests库和BeautifulSoup4库爬取新闻列表

    画图显示: import jieba from wordcloud import WordCloud import matplotlib.pyplot as plttxt = open("z ...

  4. python 网页解析库 beautifulsoup4 简介

    HTML 文档本身是结构化的文本,有一定的规则,通过它的结构可以简化信息提取.于是,就有了lxml.pyquery.BeautifulSoup等网页信息提取库.一般我们会用这些库来提取网页信息.其中, ...

  5. 【python+beautifulsoup4】Python中安装bs4后,pycharm报错ModuleNotFoundError: No module named 'bs4'...

    本文主要分享关于在对应python版本中安装beautifulsoup之后,在代码执行时还会提示"No module named 'bs4'"的问题. 安装beautifsoup4 ...

  6. Python爬虫beautifulsoup4常用的解析方法总结

    摘要 如何用beautifulsoup4解析各种情况的网页 beautifulsoup4的使用 关于beautifulsoup4,官网已经讲的很详细了,我这里就把一些常用的解析方法做个总结,方便查阅. ...

  7. day 03 selenium与Beautifulsoup4的原理与使用

    #爬取京东商品数据import timefrom selenium import webdriverfrom selenium.webdriver.common.keys import Keysdef ...

  8. python模块--BeautifulSoup4 和 lxml

    BeautifulSoup4和lxml 这两个库主要是解析html/xml文档,BeautifulSoup 用来解析 HTML 比较简单,API非常人性化,支持CSS选择器. Python标准库中的H ...

  9. 使用pip安装BeautifulSoup4模块

    1.测试是否安装了BeautifulSoup4模块 import bs4 print bs4 执行报错说明没有安装该模块 Traceback (most recent call last):File ...

最新文章

  1. c语言解析sql语句_sql语句面试50题(Mysql版附解析)
  2. 文件系统vs对象存储——选型和趋势
  3. Bootstrap入门(二十一)组件15:警告框
  4. ROracle Mysql_ROracle包查询数据库中文乱码
  5. python redis模块常用_Python基础-redis模块使用
  6. IPerf——网络测试工具介绍与源码解析(3)
  7. Java多线程编程(1)--Java中的线程
  8. 加载语音license command
  9. Dev TreeList常用用法
  10. 微处理器OpenRisc、SPARC、RISC-V架构
  11. bug-箭头函数中this指向的问题
  12. unity3D实现小游戏案例--弹开小球
  13. 第二讲:PN结与二极管的特性
  14. 移动国际漫游电话费用计算
  15. 波士顿动力SpotMini改造有胳膊半人马,这家意大利创企打造极致机械手臂
  16. 开始写博客之学习编程的重要性
  17. DDR1 和 DDR2 双靶点抑制剂的设计合成及其抗炎作用研究
  18. 《第五项修炼》读书笔记
  19. OpenFOAM当中监测力和阻力系数
  20. 移动端应用APP的分类(WebApp、HybridApp、 NativeApp)

热门文章

  1. Oracle 定义变量的方法
  2. angular项目如何分层
  3. linux系统日志_第十二章:走进Linux世界——系统日志管理,日志轮转。
  4. 两个时间计算毫秒在线_蹲坑英语时间之in a jiffy
  5. 干货 | Vim Cheat Sheet快捷键汇总
  6. mysql 主键 uniqo_优衣库某处SQL注入可导致移动平台被劫持
  7. 企业深入使用微服务后会面临哪些问题?云原生全链路灰度给了新思路
  8. 阿里云徐立:面向容器和 Serverless Computing 的存储创新
  9. GitHub Action + ACK:云原生 DevOps 落地利器
  10. 开放下载!解锁 Serverless 从入门到实战大“橙”就