给出一段html
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
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, "html.parser")
获得标题的结构
print(soup.title)
print(soup.title.name)
print(soup.title.string) # 获取标签内部的具体文字
output:
<title>The Dormouse's story</title>
title
The Dormouse's story
print(soup.p)
output:
<p class="title"><b>The Dormouse's story</b></p>
查看标签的所以属性:
所有属性都可以打出来,是一个字典类型
print(soup.a.attrs)
output:
{'href': 'http://example.com/elsie', 'class': ['sister'], 'id': 'link1'}
print(soup.a['href']) # 查看某个具体属性
print(soup.a.get('href')) # 通过get()函数查看具体属性
output:
http://example.com/elsie
http://example.com/elsie
soup.p['class']="new story" # 修改某个具体属性
del soup.p['class'] # 删除某个具体属性
find_all可以查找所以包含对应内容的结构,返回的是一个list
print(soup.find_all('a')) # 寻找所以包含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>]
find 函数:
find(name, attrs, recursive, text, **wargs) # recursive 递归的,循环的
这些参数相当于过滤器一样可以进行筛选处理。不同的参数过滤可以应用到以下情况:
- 查找标签,基于name参数
- 查找文本,基于text参数
- 基于正则表达式的查找
- 查找标签的属性,基于attrs参数
- 基于函数的查找
print(soup.find(id='link3')
print(soup.find('p', class_='title'))
print(soup.find(attrs={'class': 'title'}))
结果为:
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
<p class="title"><b>The Dormouse's story</b></p>
<p class="title"><b>The Dormouse's story</b></p>
print(soup.get_text())
结果为:
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;
and they lived at the bottom of a well.
...