其他分享
首页 > 其他分享> > beautifulsoup4笔记

beautifulsoup4笔记

作者:互联网

beautifulsoup4

https://beautifulsoup.cn/#id28

功能:从HTML或者XML文件中提取数据,将一段文档传入BeautifulSoup 的构造方法,就能得到一个文档的对象, 可以传入一段字符串或一个文件句柄。

文档会被转换编码;

soup选择最适合的解析器来解析这段文档,html文档被转换成复杂的树形结构,每个节点都是python对象,被归纳为四类:

tag

我将其理解为html中的标签。如soup.a。

name

tag.name每个tag自己的名字。

attributes

tag.attrs获取tag的属性,一个tag可能有多个属性;

tag['class'];

tag['class']='wumingzhibei';

del tag['class'];

soup.a.attrs 

{'href': 'http://example.com/elsie', 'class': ['sister'], 'id': 'link1'}

soup.a['id']

'link1'

多值属性

css_soup = BeautifulSoup('<p class="body strikeout"></p>')
css_soup.p['class']

['body', 'strikeout']

css_soup = BeautifulSoup('<p class="body"></p>')
css_soup.p['class']

['body']

#如果某个属性看起来好像有多个值,但在任何版本的HTML定义中都没有被定义为多值属性,那么Beautiful Soup会将这个属性作为字符串返回
id_soup = BeautifulSoup('<p id="my id"></p>')
id_soup.p['id']

'my id' 注:id属性只有一个值。

# 将tag转换成字符串时,多值属性会合并为一个值
rel_soup = BeautifulSoup('<p>Back to the <a rel="index">homepage</a></p>')
rel_soup.a['rel']

['index']

rel_soup.a['rel'] = ['index','contents']
rel_soup.p

# 如果转换的文档是XML格式,那么tag中不包含多值属性
xml_soup = BeautifulSoup('<p class="body strikeout"></p>', 'xml')
xml_soup.p['class']

'body strikeout'

牛刀小试

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="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, 'html.parser')
print(soup.prettify())

# 简单的浏览结构化数据的方法
soup.title
<title>The Dormouse's story</title>
# 标签名
soup.title.name

'title'

# 文字
soup.title.string

"The Dormouse's story"

soup.p
<p class="title"><b>The Dormouse's story</b></p>
soup.find('p')

同上

# 查找所有的p标签
soup.find_all('p')
[<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 class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
 <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
 <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;
 and they lived at the bottom of a well.</p>,
 <p class="story">...</p>]
soup.find_all('a')
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
 <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
 <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
# 获得文字内容
for name in soup.find_all('a'):
    print(name.get_text())

Elsie
Lacie
Tillie

# 获得属性值
for link in soup.find_all('a'):
    print(link.get('href'))

http://example.com/elsie
http://example.com/lacie
http://example.com/tillie

可以遍历的字符串

soup = BeautifulSoup('<b class="boldest">Extremely bold</b>')
tag = soup.b
type(tag)

bs4.element.Tag

tag.string

'Extremely bold'

type(tag.string)

bs4.element.NavigableString

# 字符串的转换
# 将NavigableString--》unicode
unicode_string = str(tag.string)
unicode_string

'Extremely bold'

type(unicode_string)

str

# 替换字符串
tag.string.replace_with("no longer bold")
tag

注释及特殊字符串

遍历文档树

soup = BeautifulSoup(html_doc, 'html.parser')
soup

子节点

# tag的名字
soup.title
<title>The Dormouse's story</title>
# 获取<body>标签中的第一个<b>标签
soup.body.b
<b>The Dormouse's story</b>
# 通过点取属性的方式只能获得当前名字的第一个tag
soup.a
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
# 如果想要得到所有的<a>标签,或是通过名字得到比一个tag更多的内容的时候,就需要用到 Searching the tree 中描述的方法,比如: find_all()
soup.find_all('a')
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
 <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
 <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

.contents 和 .children

head_tag = soup.head
head_tag
<head><title>The Dormouse's story</title></head>
# tag的 .contents 属性可以将tag的子节点以列表的方式输出
head_tag.contents
[<title>The Dormouse's story</title>]
title_tag = head_tag.contents[0]
title_tag
<title>The Dormouse's story</title>
title_tag.contents

["The Dormouse's story"]

# BeautifulSoup 对象本身一定会包含子节点
len(soup.contents)

1

soup.contents[0].name

'html'

# 字符串没有 .contents 属性,因为字符串没有子节点
text = title_tag.contents[0]
text.contents

AttributeError: 'NavigableString' object has no attribute 'contents'

# 通过tag的 .children 生成器,可以对tag的子节点进行循环
for child in title_tag.children:
    print(child)

The Dormouse's story

.descendants

head_tag.contents
[<title>The Dormouse's story</title>]
# .descendants 属性可以对所有tag的子孙节点进行递归循环
for child in head_tag.descendants:
    print(child)

title_tag.string

"The Dormouse's story"

# tag只有一个子节点,那么这个tag也可以使用 .string 方法
head_tag

head_tag.contents

head_tag.string

"The Dormouse's story"

# tag包含了多个子节点
print(soup.html.string)

None

.strings 和 stripped_strings

# 如果tag中包含多个字符串,可以使用 .strings 来循环获取
for string in soup.strings:
    print(repr(string))

"The Dormouse's story"
'\n'
'\n'
"The Dormouse's story"
'\n'
'Once upon a time there were three little sisters; and their names were\n'
'Elsie'
',\n'
'Lacie'
' and\n'
'Tillie'
';\nand they lived at the bottom of a well.'
'\n'
'...'
'\n'

for string in soup.stripped_strings:
    print(repr(string))

"The Dormouse's story"
"The Dormouse's 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.'
'...'

父节点

title_tag.parent

title_tag.string.parent

html_tag = soup.html
type(html_tag.parent)

bs4.BeautifulSoup

# 通过元素的 .parents 属性可以递归得到元素的所有父辈节点
link = soup.a
link

for parent in link.parents:
    if parent is None:
        print(parent)
    else:
        print(parent.name)

p
body
html
[document]

兄弟节点

sibling_soup = BeautifulSoup("<a><b>text1</b><c>text2</c></b></a>")
sibling_soup
print(sibling_soup.prettify())

sibling_soup.b.next_sibling

text2

sibling_soup.c.previous_sibling

回退和前进

搜索文档树

过滤器

字符串

正则表达式

列表

true

方法

find_all()

find_all( name , attrs , recursive , string , **kwargs )

name参数

soup.find_all("title")

keyword参数

soup.find_all(id='link2')
soup.find_all(href=re.compile("elsie"))
soup.find_all(id=True)
soup.find_all(href=re.compile("elsie"), id='link1')

有些tag属性在搜索不能使用,比如HTML5中的 data-* 属性:

data_soup = BeautifulSoup('<div data-foo="value">foo!</div>')
data_soup.find_all(data-foo="value")
data_soup.find_all(attrs={"data-foo": "value"})

按css搜索

string参数

limit参数

recursive参数

像调用 find_all() 一样调用tag

find()
find_parents() 和 find_parent()
find_next_siblings() 和 find_next_sibling()
find_previous_siblings() 和 find_previous_sibling()
find_all_next() 和 find_next()
find_all_previous() 和 find_previous()

修改文档树

输出

格式化输出
压缩输出
输出格式
get_text()

标签:story,string,笔记,Dormouse,soup,tag,beautifulsoup4,find
来源: https://www.cnblogs.com/Cookie-Jing/p/16025767.html