百度联盟做网站赚钱,网站建设多少钱裤,可以发布推广引流的悬赏平台,二手车交易网站怎么做文章目录 beautifulsoup一. beautifulsoup的简单使用1、安装2、如何使用3、对象的种类 二、beautifulsoup的遍历文档树2.1 子节点.contents 和 .children descendants2.2 节点内容.string.text 2.3 多个内容.strings**.stripped_strings** 2.4 父节点.parent.parents 三、beaut… 文章目录 beautifulsoup一. beautifulsoup的简单使用1、安装2、如何使用3、对象的种类 二、beautifulsoup的遍历文档树2.1 子节点.contents 和 .children descendants2.2 节点内容.string.text 2.3 多个内容.strings**.stripped_strings** 2.4 父节点.parent.parents 三、beautiful的搜索文档树3.1 find_allname 参数keyword 参数text 参数limit 参数 3.3 find()3.4 find_parents() 和 find_parent() 四、beautifulsoup的css选择器4.1 通过标签名查找4.2 通过类名查找4.3 id名查找4.4 组合查找4.5 属性查找 五.真实案例1、使用 bs4提取豆瓣图书信息2、匹配三国演义中的回合 并写入html文本中3、匹配天气信息 城市与温度4、匹配广州二手房 房源信息 beautifulsoup
一. beautifulsoup的简单使用
1、安装
Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器如果我们不安装它则 Python 会使用 Python默认的解析器lxml 解析器更加强大速度更快推荐安装。
pip install beautifulsoup42、如何使用
这是一个html的简单页面
html_doc
htmlheadtitleThe Dormouses story/title/head
body
p classtitlebThe Dormouses story/b/pp classstoryOnce upon a time there were three little sisters; and their names were
a hrefhttp://example.com/elsie classsister idlink1Elsie/a,
a hrefhttp://example.com/lacie classsister idlink2Lacie/a and
a hrefhttp://example.com/tillie classsister idlink3Tillie/a;
and they lived at the bottom of a well./pp classstory.../p使用BeautifulSoup解析这段代码,能够得到一个 BeautifulSoup 的对象,并能按照标准的缩进格式的结构输出:
from bs4 import BeautifulSoup
soup BeautifulSoup(html_doc, lxml)
# html进行美化
print(soup.prettify())这里介绍几个简单的浏览结构化数据的方法
soup.title # 获取标签title
# titleThe Dormouses story/titlesoup.title.name # 获取标签名称
# titlesoup.title.string # 获取标签title内的内容
# The Dormouses storysoup.title.parent # 获取父级标签soup.title.parent.name # 获取父级标签名称
# headsoup.p
# p classtitlebThe Dormouses story/b/psoup.p[class] # 获取p的class属性值
# titlesoup.a
# a classsister hrefhttp://example.com/elsie idlink1Elsie/asoup.find_all(a)
# [a classsister hrefhttp://example.com/elsie idlink1Elsie/a,
# a classsister hrefhttp://example.com/lacie idlink2Lacie/a,
# a classsister hrefhttp://example.com/tillie idlink3Tillie/a]soup.find(idlink3) # 获取id为link3的标签
# a classsister hrefhttp://example.com/tillie idlink3Tillie/a3、对象的种类
Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为种
Tag , NavigableString , BeautifulSoup , Comment .
Tag
通俗点讲就是 HTML 中的一个个标签Tag 对象与XML或HTML原生文档中的tag相同:
soup BeautifulSoup(b classboldestExtremely bold/b)
tag soup.b
type(tag)
# class bs4.element.Tagtag的名字 soup对象我以下面的例子为准操作文档树最简单的方法就是告诉它你想获取的tag的name.如果想获取 标签,只要用 soup.head
soup.head
# headtitleThe Dormouses story/title/headsoup.title
# titleThe Dormouses story/titlename和attributes属性 Tag有很多方法和属性,现在介绍一下tag中最重要的属性: name和attributes
每个tag都有自己的名字,通过 .name 来获取:
tag.name
# btag[class]
# boldesttag.attrs
# {class: boldest}tag的属性可以被添加,删除或修改. 再说一次, tag的属性操作方法与字典一样了解
tag[class] verybold
tag[id] 1
tag
# blockquote classverybold id1Extremely bold/blockquotedel tag[class]
del tag[id]
tag
# blockquoteExtremely bold/blockquotetag[class]
# KeyError: class
print(tag.get(class))
# NoneNavigableString(字符串) 我们既然已经得到了标签的内容我们想获取具体标签内部的文字怎么办呢 字符串常被包含在tag内.Beautiful Soup用 NavigableString 类来包装tag中的字符串。
tag.string
# Extremely bold
type(tag.string)
# class bs4.element.NavigableStringBeautifulSoup BeautifulSoup 对象表示的是一个文档的全部内容.大部分时候,可以把它当作 Tag 对象是一个特殊的 Tag我们可以分别获取它的类型名称以及属性。
print(type(soup.name))
# class str
print(soup.name)
# [document]
print(soup.attrs)
# {} 空字典Comment html_doc‘ ’
soup BeautifulSoup(html_doc, ‘html.parser’)
print(soup.a.string) # Elsie print(type(soup.a.string)) # class ‘bs4.element.Comment’
二、beautifulsoup的遍历文档树
我们使用下面的例子我们来演示下面的几个功能
html_doc
htmlheadtitleThe Dormouses story/title/headbody
p classtitlebThe Dormouses story/b/pp classstoryOnce upon a time there were three little sisters; and their names were
a hrefhttp://example.com/elsie classsister idlink1Elsie/a,
a hrefhttp://example.com/lacie classsister idlink2Lacie/a and
a hrefhttp://example.com/tillie classsister idlink3Tillie/a;
and they lived at the bottom of a well./pp classstory.../p
from bs4 import BeautifulSoup
soup BeautifulSoup(html_doc, html.parser)2.1 子节点
一个Tag可能包含多个字符串或其它的Tag,这些都是这个Tag的子节点.Beautiful Soup提供了许多操作和遍历子节点的属性.
.contents 和 .children
tag的 .contents 属性可以将tag的子节点以列表的方式输出:
head_tag soup.head
head_tag
# headtitleThe Dormouses story/title/headhead_tag.contents
[titleThe Dormouses story/title]title_tag head_tag.contents[0]
title_tag
# titleThe Dormouses story/title
title_tag.contents
# [uThe Dormouses story]字符串没有 .contents 属性,因为字符串没有子节点:
text title_tag.contents[0]
text.contents
# AttributeError: NavigableString object has no attribute contents.children它返回的不是一个 list不过我们可以通过遍历获取所有子节点。我们打印输出 .children 看一下可以发现它是一个 list 生成器对象 通过tag的 .children 生成器,可以对tag的子节点进行循环:
print(title_tag.children) # list_iterator object at 0x101b78860
print(type(title_tag.children)) # class list_iteratorfor child in title_tag.children:print(child)# The Dormouses storydescendants
.contents 和 .children 属性仅包含tag的直接子节点.例如,head标签只有一个直接子节点title
head_tag.contents
# [titleThe Dormouses story/title]但是title标签也包含一个子节点:字符串 “The Dormouse’s story”,这种情况下字符串 “The Dormouse’s story”也属于head标签的子孙节点.
.descendants 属性可以对所有tag的子孙节点进行递归循环 。
for child in head_tag.descendants:print(child)# titleThe Dormouses story/title# The Dormouses story上面的例子中, head标签只有一个子节点,但是有2个子孙节点:head节点和head的子节点, BeautifulSoup 有一个直接子节点(html节点),却有很多子孙节点:
len(list(soup.children))
# 1
len(list(soup.descendants))
# 252.2 节点内容
.string
如果tag只有一个 NavigableString 类型子节点,那么这个tag可以使用 .string 得到子节点。如果一个tag仅有一个子节点,那么这个tag也可以使用 .string 方法,输出结果与当前唯一子节点的 .string 结果相同。
通俗点说就是如果一个标签里面没有标签了那么 .string 就会返回标签里面的内容。如果标签里面只有唯一的一个标签了那么 .string 也会返回最里面的内容。例如
print (soup.head.string)
#The Dormouses story
# titlebThe Dormouses story/b/title
print (soup.title.string)
#The Dormouses story如果tag包含了多个子节点,tag就无法确定string 方法应该调用哪个子节点的内容, .string 的输出结果是 None
print (soup.html.string)
#None.text
如果tag包含了多个子节点, text则会返回内部所有文本内容
print (soup.html.text)注意
strings和text都可以返回所有文本内容
区别text返回内容为字符串类型 strings为生成器generator
2.3 多个内容
.strings .stripped_strings 属性
.strings
获取多个内容不过需要遍历获取比如下面的例子
for string in soup.strings:print(repr(string))\n
The Dormouses story
\n
\n
The Dormouses story
\n
Once upon a time there were three little sisters; and their names were\n
Elsie
,\n
Lacieand\n
Tillie
;\nand they lived at the bottom of a well.
\n
...
\n .stripped_strings
输出的字符串中可能包含了很多空格或空行,使用 .stripped_strings 可以去除多余空白内容
for string in soup.stripped_strings:print(repr(string))The Dormouses story
The Dormouses story
Once upon a time there were three little sisters; and their names were
Elsie
,
Lacie
and
Tillie
;\nand they lived at the bottom of a well.
...2.4 父节点
.parent
通过 .parent 属性来获取某个元素的父节点.在例子“爱丽丝”的文档中,head标签是title标签的父节点:
title_tag soup.title
title_tag
# titleThe Dormouses story/title
title_tag.parent
# headtitleThe Dormouses story/title/head文档的顶层节点比如html的父节点是 BeautifulSoup 对象:
html_tag soup.html
type(html_tag.parent)
# class bs4.BeautifulSoup.parents
通过元素的 .parents 属性可以递归得到元素的所有父辈节点,下面的例子使用了 .parents 方法遍历了a标签到根节点的所有节点.
link soup.a
link
# a classsister hrefhttp://example.com/elsie idlink1Elsie/a
for parent in link.parents:if parent is None:print(parent)else:print(parent.name)
# p
# body
# html
# [document]
# None三、beautiful的搜索文档树
3.1 find_all
find_all( name , attrs , recursive , string , **kwargs ) name: 一个字符串或正则表达式用于指定要查找的标签名称。如果传入 True则匹配任何标签。 attrs: 一个字典或 None。如果传入字典字典中的键值对将被用来匹配标签的属性。例如{‘class’: ‘foo’} 将匹配所有具有 class“foo” 属性的标签。 recursive: 一个布尔值。如果为 True默认值则在所有后代中递归搜索匹配的标签如果为 False则只在当前标签的直接子标签中搜索。 string: 一个字符串或正则表达式用于匹配标签内的文本。如果传入字符串Beautiful Soup 将查找包含该字符串的标签如果传入正则表达式则使用该正则表达式来匹配标签内的文本。 **kwargs: 额外的关键字参数这些参数将被传递给 find_all 方法的内部实现用于进一步定制搜索条件。
soup.find_all(title)
# [titleThe Dormouses story/title]soup.find_all(p, title)
# [p classtitlebThe Dormouses story/b/p]soup.find_all(a)
# [a classsister hrefhttp://example.com/elsie idlink1Elsie/a,
# a classsister hrefhttp://example.com/lacie idlink2Lacie/a,
# a classsister hrefhttp://example.com/tillie idlink3Tillie/a]soup.find_all(idlink2)
# [a classsister hrefhttp://example.com/lacie idlink2Lacie/a]import re
# 模糊查询 包含sisters的就可以
soup.find(stringre.compile(sisters))
# Once upon a time there were three little sisters; and their names were\n有几个方法很相似,还有几个方法是新的,参数中的 string 和 id 是什么含义? 为什么 find_all(p, title) 返回的是CSS Class为”title”的p标签? 我们来仔细看一下 find_all() 的参数.
name 参数
name 参数可以查找所有名字为 name 的tag,字符串对象会被自动忽略掉.
简单的用法如下:
soup.find_all(title)
# [titleThe Dormouses story/title]1 传字符串 最简单的过滤器是字符串.在搜索方法中传入一个字符串参数,Beautiful Soup会查找与字符串完整匹配的内容,下面的例子用于查找文档中所有的标签
soup.find_all(b)
# [bThe Dormouses story/b]2 传正则表达式
import re
for tag in soup.find_all(re.compile(^b)):print(tag.name)
# body
# b3 传列表 如果传入列表参数,Beautiful Soup会将与列表中任一元素匹配的内容返回.下面代码找到文档中所有a标签和b标签
soup.find_all([a, b])
# [bThe Dormouses story/b,
# a classsister hrefhttp://example.com/elsie idlink1Elsie/a,
# a classsister hrefhttp://example.com/lacie idlink2Lacie/a,
# a classsister hrefhttp://example.com/tillie idlink3Tillie/a]keyword 参数
如果一个指定名字的参数不是搜索内置的参数名,搜索时会把该参数当作指定名字tag的属性来搜索,如果包含一个名字为 id 的参数,Beautiful Soup会搜索每个tag的”id”属性.
soup.find_all(idlink2)
# [a classsister hrefhttp://example.com/lacie idlink2Lacie/a]import re
# 超链接包含elsie标签
print(soup.find_all(hrefre.compile(elsie)))
# [a classsister hrefhttp://example.com/elsie idlink1Elsie/a]
# 以The作为开头的字符串
print(soup.find_all(textre.compile(^The)))
# [The Dormouses story, The Dormouses story]
# class选择器包含st的节点
print(soup.find_all(class_re.compile(st)))搜索指定名字的属性时可以使用的参数值包括 字符串 , 正则表达式 , 列表, True . 下面的例子在文档树中查找所有包含 id 属性的tag,无论 id 的值是什么:
soup.find_all(idTrue)
# [a classsister hrefhttp://example.com/elsie idlink1Elsie/a,
# a classsister hrefhttp://example.com/lacie idlink2Lacie/a,
# a classsister hrefhttp://example.com/tillie idlink3Tillie/a]使用多个指定名字的参数可以同时过滤tag的多个属性:
soup.find_all(hrefre.compile(elsie), idlink1)
# [a classsister hrefhttp://example.com/elsie idlink1three/a]在这里我们想用 class 过滤不过 class 是 python 的关键词这怎么办加个下划线就可以:
print(soup.find_all(a, class_sister))
[a classsister hrefhttp://example.com/elsie idlink1Elsie/a,
a classsister hrefhttp://example.com/lacie idlink2Lacie/a,
a classsister hrefhttp://example.com/tillie idlink3Tillie/a
]通过 find_all() 方法的 attrs 参数定义一个字典参数来搜索包含特殊属性的tag: ]
data_soup.find_all(attrs{data-foo: value})
# [div data-foovaluefoo!/div]注意如何查看条件id和class同时存在时的写法
data_soup.find_all(attrs{data-foo: value})
# [div data-foovaluefoo!/div]注意如何查看条件id和class同时存在时的写法
print(soup.find_all(b, class_story, idx))
print(soup.find_all(b, attrs{class:story, id:x}))text 参数
通过 text 参数可以搜搜文档中的字符串内容.与 name 参数的可选值一样, text 参数接受 字符串 , 正则表达式 , 列表, True.
import reprint(soup.find_all(textElsie))
# [Elsie]print(soup.find_all(text[Tillie, Elsie, Lacie]))
# [Elsie, Lacie, Tillie]# 只要包含Dormouse就可以
print(soup.find_all(textre.compile(Dormouse)))
# [The Dormouses story, The Dormouses story]limit 参数
find_all() 方法返回全部的搜索结构,如果文档树很大那么搜索会很慢.如果我们不需要全部结果,可以使用 limit 参数限制返回结果的数量.效果与SQL中的limit关键字类似,当搜索到的结果数量达到 limit 的限制时,就停止搜索返回结果.
print(soup.find_all(a,limit2))
print(soup.find_all(a)[0:2])
[a classsister hrefhttp://example.com/elsie idlink1Elsie/a,
a classsister hrefhttp://example.com/lacie idlink2Lacie/a]3.3 find()
find(name , attrs , recursive , string , **kwargs ) name: 一个字符串或正则表达式用于指定要查找的标签名称。如果设置为 None 或省略则匹配任何标签。 attrs: 一个字典用于指定要查找的标签的属性。如果属性字典中的键值对完全匹配一个标签的属性则该标签会被返回。如果设置为 None 或省略则不进行属性匹配。 recursive: 一个布尔值。如果为 True默认值则在所有后代中递归搜索匹配的标签如果为 False则只在当前标签的直接子标签中搜索。 string: 一个字符串或正则表达式用于匹配标签内的文本。如果传入字符串find 将查找包含该字符串的第一个标签如果传入正则表达式则使用该正则表达式来匹配标签内的文本。 **kwargs: 额外的关键字参数这些参数可以用于指定其他搜索条件如 limit限制返回的结果数量等。
find_all() 方法将返回文档中符合条件的所有tag,尽管有时候我们只想得到一个结果.比如文档中只有一个body标签,那么使用 find_all() 方法来查找body标签就不太合适, 使用 find_all 方法并设置 limit1 参数不如直接使用 find() 方法.下面两行代码是等价的:
soup.find_all(title, limit1)
# [titleThe Dormouses story/title]soup.find(title)
# titleThe Dormouses story/title唯一的区别是 find_all() 方法的返回结果是值包含一个元素的列表,而 find() 方法直接返回结果.
find_all() 方法没有找到目标是返回空列表, find() 方法找不到目标时,返回 None .
print(soup.find(nosuchtag))
# Nonesoup.head.title 是 tag的名字 方法的简写.这个简写的原理就是多次调用当前tag的 find() 方法:
soup.head.title
# titleThe Dormouses story/titlesoup.find(head).find(title)
# titleThe Dormouses story/title3.4 find_parents() 和 find_parent()
a_string soup.find(textLacie)
print(a_string) # Lacieprint(a_string.find_parent())
# a classsister hrefhttp://example.com/lacie idlink2Lacie/a
print(a_string.find_parents())
print(a_string.find_parent(p))p classstoryOnce upon a time there were three little sisters; and their names werea classsister hrefhttp://example.com/elsie idlink1Elsie/a,a classsister hrefhttp://example.com/lacie idlink2Lacie/a anda classsister hrefhttp://example.com/tillie idlink3Tillie/a;and they lived at the bottom of a well.
/p四、beautifulsoup的css选择器
我们在写 CSS 时标签名不加任何修饰类名前加点id名前加 #在这里我们也可以利用类似的方法来筛选元素用到的方法是 **soup.select()**返回类型是 list
4.1 通过标签名查找
print(soup.select(title)) #[titleThe Dormouses story/title]
print(soup.select(b)) #[bThe Dormouses story/b]4.2 通过类名查找
print(soup.select(.sister))
[a classsister hrefhttp://example.com/elsie idlink1Elsie/a,
a classsister hrefhttp://example.com/lacie idlink2Lacie/a,
a classsister hrefhttp://example.com/tillie idlink3Tillie/a]4.3 id名查找
print(soup.select(#link1))
# [a classsister hrefhttp://example.com/elsie idlink1Elsie/a]4.4 组合查找
组合查找即和写 class 文件时标签名与类名、id名进行的组合原理是一样的例如查找 p 标签中id 等于 link1的内容二者需要用空格分开。
print(soup.select(p #link2))#[a classsister hrefhttp://example.com/lacie idlink2Lacie/a]直接子标签查找
print(soup.select(p #link2))
# [a classsister hrefhttp://example.com/lacie idlink2Lacie/a]查找既有class也有id选择器的标签
a_string soup.select(.story#test)查找有多个class选择器的标签
a_string soup.select(.story.test)查找有多个class选择器和一个id选择器的标签
a_string soup.select(.story.test#book)4.5 属性查找
查找时还可以加入属性元素属性需要用中括号括起来注意属性和标签属于同一节点所以中间不能加空格否则会无法匹配到。
print(soup.select(a[hrefhttp://example.com/tillie]))
#[a classsister hrefhttp://example.com/tillie idlink3Tillie/a]select 方法返回的结果都是列表形式可以遍历形式输出然后用 get_text() 方法来获取它的内容
for title in soup.select(a):print (title.get_text())
Elsie
Lacie
Tillie五.真实案例
1、使用 bs4提取豆瓣图书信息 from bs4 import BeautifulSoup
soup BeautifulSoup(open(../素材/豆瓣.html, r), lxml)# 匹配图片地址
print(soup.find_all(img))
for i in soup.find_all(img):print(i.attrs) # 获取图片连接地址# 获取标题 简介 评分等信息h soup.find_all(div, class_detail-frame)
for i in h:# print(i.text) # 获取当前节点里所有的文本内容print(i.a.text) # 获取标题 超链接里面的文本内容print(i.find(span, class_font-small color-lightgray).text) # 获取评分print(i.find(p, color-gray).text) # 获取简介print(i.find_all(p)[-1].text) # 获取简介
2、匹配三国演义中的回合 并写入html文本中
from bs4 import BeautifulSoup# 进行请求
# 获取页面内容
con open(../素材/三国演义.html, r)
# 参数 页面内容 解析器
soup BeautifulSoup(con, lxml)
title_list soup.select(.book-muluullia)with open(./爬取三国演义.html, w, encodingGBK) as f:for t in title_list:# 输出文章标题title t.text# 获取文章地址href t[href]url https://www.shicimingju.com/hrefprint(url)f.write(fa href{url} target_blank{title}/abr /)3、匹配天气信息 城市与温度
只要城市与气温。
from bs4 import BeautifulSoup
ALL_DATA []
soup BeautifulSoup(open(../素材/匹配天气.html, r), lxml)
conMidtab soup.find(div,class_conMidtab)
# 获取所有的天气信息表格
tables conMidtab.find_all(table)
for table in tables:# 过滤掉标题行trs table.find_all(tr)[2:]for index, tr in enumerate(trs):tds tr.find_all(td)# print(index, tds)# 获取城市和天气city_td tds[0]temp_td tds[3]# 过滤掉表格左侧的省/直辖市if index 0:city_td tds[1]temp_td tds[4]city_td list(city_td.stripped_strings)[0]temp_td list(temp_td.stripped_strings)[0]ALL_DATA.append({city:city_td,temp:temp_td})print(ALL_DATA)
4、匹配广州二手房 房源信息
from bs4 import BeautifulSoupsoup BeautifulSoup(open(../素材/二手房详情页.html, r), lxml)
# 通过select方式进行获取
# sidefixedbox soup.select(.sidefixedbox#sidefixedbox)
# print(sidefixedbox[0].text)
# 通过属性
sidefixedbox soup.find(div, attrs{class: sidefixedbox, id: sidefixedbox}).text
print(sidefixedbox)