一、Beautiful Soup的简介

  简单来说,Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据。官方解释:Beautiful Soup提供一些简单的、python式的函数用来处理导航、搜索、修改分析树等功能。它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序。Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码。你不需要考虑编码方式,除非文档没有指定一个编码方式,这时,Beautiful Soup就不能自动识别编码方式了。然后,你仅仅需要说明一下原始编码方式就可以了。Beautiful Soup已成为和lxml、html6lib一样出色的python解释器,为用户灵活地提供不同的解析策略或强劲的速度。

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

三、 Beautiful Soup的简单使用

'''
pip3 install beautifulsoup4 # 安装bs4
pip3 install lxml # 下载lxml解析器
'''
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="sister"><b>$37</b></p>
<p class="story" id="p">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" >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>
""" # 从bs4中导入BeautifulSoup
from bs4 import BeautifulSoup # 调用BeautifulSoup实例化得到一个soup对象
# 参数一: 解析文本
# 参数二:
# 参数二: 解析器(html.parser、lxml...)
soup = BeautifulSoup(html_doc, 'lxml') print(soup)
print('*' * 100)
print(type(soup))
print('*' * 100)
# 文档美化
html = soup.prettify()
print(html)

四、 Beautiful Soup之遍历文档树

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="sister"><b>$37</b></p>
<p class="story" id="p">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" >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, 'lxml') '''
遍历文档树:
1、直接使用
2、获取标签的名称
3、获取标签的属性
4、获取标签的内容
5、嵌套选择
6、子节点、子孙节点
7、父节点、祖先节点
8、兄弟节点
''' # 1、直接使用
print(soup.p) # 查找第一个p标签
print(soup.a) # 查找第一个a标签 # 2、获取标签的名称
print(soup.head.name) # 获取head标签的名称 # 3、获取标签的属性
print(soup.a.attrs) # 获取a标签中的所有属性
print(soup.a.attrs['href']) # 获取a标签中的href属性 # 4、获取标签的内容
print(soup.p.text) # $37 # 5、嵌套选择
print(soup.html.head) # 6、子节点、子孙节点
print(soup.body.children) # body所有子节点,返回的是迭代器对象
print(list(soup.body.children)) # 强转成列表类型 print(soup.body.descendants) # 子孙节点
print(list(soup.body.descendants)) # 子孙节点 # 7、父节点、祖先节点
print(soup.p.parent) # 获取p标签的父亲节点
# 返回的是生成器对象
print(soup.p.parents) # 获取p标签所有的祖先节点
print(list(soup.p.parents)) # 8、兄弟节点
# 找下一个兄弟
print(soup.p.next_sibling)
# 找下面所有的兄弟,返回的是生成器
print(soup.p.next_siblings)
print(list(soup.p.next_siblings)) # 找上一个兄弟
print(soup.a.previous_sibling) # 找到第一个a标签的上一个兄弟节点
# 找到a标签上面的所有兄弟节点
print(soup.a.previous_siblings) # 返回的是生成器
print(list(soup.a.previous_siblings))

四、 Beautiful Soup之搜索文档树

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="sister"><b>$37</b></p>
<p class="story" id="p">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" >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>
"""
'''
搜索文档树:
find() 找一个
find_all() 找多个 标签查找与属性查找:
标签:
name 属性匹配
attrs 属性查找匹配
text 文本匹配 - 字符串过滤器
字符串全局匹配 - 正则过滤器
re模块匹配 - 列表过滤器
列表内的数据匹配 - bool过滤器
True匹配 - 方法过滤器
用于一些要的属性以及不需要的属性查找。 属性:
- class_
- id
''' from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'lxml') # # 字符串过滤器
# name
p_tag = soup.find(name='p')
print(p_tag) # 根据文本p查找某个标签
# # 找到所有标签名为p的节点
tag_s1 = soup.find_all(name='p')
print(tag_s1)
#
#
# # attrs
# # 查找第一个class为sister的节点
p = soup.find(attrs={"class": "sister"})
# print(p)
# # 查找所有class为sister的节点
tag_s2 = soup.find_all(attrs={"class": "sister"})
print(tag_s2) # text
text = soup.find(text="$37")
print(text)
#
#
# # 配合使用:
# # 找到一个id为link2、文本为Lacie的a标签
a_tag = soup.find(name="a", attrs={"id": "link2"}, text="Lacie")
print(a_tag) # # 正则过滤器
import re
# name
p_tag = soup.find(name=re.compile('p'))
print(p_tag) # 列表过滤器
import re
# name
tags = soup.find_all(name=['p', 'a', re.compile('html')])
print(tags) # - bool过滤器
# True匹配
# 找到有id的p标签
p = soup.find(name='p', attrs={"id": True})
print(p) # 方法过滤器
# 匹配标签名为a、属性有id没有class的标签
def have_id_class(tag):
if tag.name == 'a' and tag.has_attr('id') and tag.has_attr('class'):
return tag tag = soup.find(name=have_id_class)
print(tag)

python爬虫之beautifulsoup的使用的更多相关文章

  1. 使用Python爬虫库BeautifulSoup遍历文档树并对标签进行操作详解(新手必学)

    为大家介绍下Python爬虫库BeautifulSoup遍历文档树并对标签进行操作的详细方法与函数下面就是使用Python爬虫库BeautifulSoup对文档树进行遍历并对标签进行操作的实例,都是最 ...

  2. Python爬虫——用BeautifulSoup、python-docx爬取廖雪峰大大的教程为word文档

    版权声明:本文为博主原创文章,欢迎转载,并请注明出处.联系方式:460356155@qq.com 廖雪峰大大贡献的教程写的不错,写了个爬虫把教程保存为word文件,供大家方便下载学习:http://p ...

  3. 【Python爬虫】BeautifulSoup网页解析库

    BeautifulSoup 网页解析库 阅读目录 初识Beautiful Soup Beautiful Soup库的4种解析器 Beautiful Soup类的基本元素 基本使用 标签选择器 节点操作 ...

  4. Python爬虫之BeautifulSoup的用法

    之前看静觅博客,关于BeautifulSoup的用法不太熟练,所以趁机在网上搜索相关的视频,其中一个讲的还是挺清楚的:python爬虫小白入门之BeautifulSoup库,有空做了一下笔记: 一.爬 ...

  5. Python爬虫系列-BeautifulSoup详解

    安装 pip3 install beautifulsoup4 解析库 解析器 使用方法 优势 劣势 Python标准库 BeautifulSoup(markup,'html,parser') Pyth ...

  6. Python爬虫之Beautifulsoup模块的使用

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

  7. Python 爬虫—— requests BeautifulSoup

    本文记录下用来爬虫主要使用的两个库.第一个是requests,用这个库能很方便的下载网页,不用标准库里面各种urllib:第二个BeautifulSoup用来解析网页,不然自己用正则的话很烦. req ...

  8. 通过哪吒动漫豆瓣影评,带你分析python爬虫与BeautifulSoup快速入门【华为云技术分享】

    久旱逢甘霖 西安连着几天温度排行全国三甲,也许是<哪吒之魔童降世>的剧组买通了老天,从踩着风火轮的小朋友首映开始,就全国性的持续高温,还好今天凌晨的一场暴雨,算是将大家从中暑边缘拯救回来了 ...

  9. python爬虫之BeautifulSoup

    爬虫有时候写正则表达式会有假死现象 就是正则表达式一直在进行死循环查找 例如:https://social.msdn.microsoft.com/forums/azure/en-us/3f4390ac ...

  10. python爬虫入门--beautifulsoup

    1,beautifulsoup的中文文档:https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/ 2, from bs4 import Be ...

随机推荐

  1. Luogu_2876_[USACO07JAN]解决问题Problem Solving

    题目描述 过去的日子里,农夫John的牛没有任何题目. 可是现在他们有题目,有很多的题目. 精确地说,他们有\(P(1 \leq P \leq 300)\)道题目要做. 他们还离开了农场并且象普通人一 ...

  2. <BZOJ3032>七夕祭

    水 #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> ...

  3. rest-framework源码解析和自定义组件----版本

    版本 url中通过GET传参自定义的版本 12345678910111213141516171819202122 from django.http import HttpResponsefrom dj ...

  4. 《Effective Java》笔记45-56:通用程序设计

    将局部变量的作用域最小化,可以增强代码的可读性和可维护性,并降低出错的可能性. 要使用局部变量的作用域最小化,最有力的方法就是在第一次使用它的地方才声明,不要过早的声明. 局部变量的作用域从它被声明的 ...

  5. Spring Boot 2.x基础教程:使用 Thymeleaf开发Web页面

    通过本系列教程的前几章内容(API开发.数据访问).我们已经具备完成一个涵盖数据存储.提供HTTP接口的完整后端服务了.依托这些技能,我们已经可以配合前端开发人员,一起来完成一些前后端分离的Web项目 ...

  6. C#使用正则表达式获取HTML代码中a标签里包含指定后缀的href的值

    //C#使用正则表达式获取HTML代码中a标签里包含指定后缀的href的值,表达式如下: Regex regImg = new Regex(@"(?is)<a[^>]*?href ...

  7. 身为 Java 程序员必须掌握的 10 款开源工具!

    本文主要介绍Java程序员应该在Java学习过程中的一些基本和高级工具.如果你是一位经验丰富的Java开发人员,你可能对这些工具很熟悉,但如果不是,现在就是是开始学习这些工具的好时机.Java世界中存 ...

  8. 基于Noisy Channel Model和Viterbi算法的词性标注问题

    给定一个英文语料库,里面有很多句子,已经做好了分词,/前面的是词,后面的表示该词的词性并且每句话由句号分隔,如下图所示 对于一个句子S,句子中每个词语\(w_i\)标注了对应的词性\(z_i\).现在 ...

  9. NSURLSession的前世今生

    系统网络框架架构图 前世-NSURLConnection NSURLConnection是苹果提供的原生网络访问类,已经有10多年的历史了,它从 iOS 2.0 开始,一直到iOS9被废弃.异步方法在 ...

  10. mysql中用SQL增加、删除字段,修改字段名

    CREATE TABLE `tuser` ( `id` int(11) NOT NULL, `name` varchar(32) DEFAULT NULL, PRIMARY KEY (`id`) ) ...