导包并以以下部分网页源码为例,过程也即增删改查:
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>
"""
soup = BeautifulSoup(html_doc, 'lxml')
修改tag的名称以及属性
tag_p = soup.p
print(tag_p)
tag_p.name = 'p1' # 修改标签名称
tag_p['class'] = 'content' # 修改标签属性
print(tag_p)
成功修改:
修改string,用当前的内容替代原来的内容
tag_p = soup.p
print(tag_p.string)
tag_p.string = 'Hello World!'
print(tag_p.string)
增加string
tag_p = soup.p
print(tag_p)
tag_p.append('江峰')
print(tag_p)
decompose() 方法删除段落
r = soup.find(class_='title')
print(r)
print('_' * 100)
r.decompose()
print(soup)
如图r已经从soup中删除。