简介
可以通过 attrs 获取和修改属性。
示例:获取属性值
代码:
from bs4 import BeautifulSoup
html_content = '''
<div id="content" data="你好">测试01</div>
<div>测试03</div>
'''.strip()
soup = BeautifulSoup(html_content, 'html.parser')
content_div = soup.select_one("#content")
print(content_div)
print('name:', content_div.name)
print('attrs.data:', content_div.attrs['data'])
print('text:', content_div.get_text())
执行结果:
<div data="你好" id="content">测试01</div>
name: div
attrs.data: 你好
text: 测试01
示例:判断有无某个属性
from bs4 import BeautifulSoup
html_content = '''
<div id="content" data="你好">测试01</div>
<div>测试03</div>
'''.strip()
soup = BeautifulSoup(html_content, 'html.parser')
content_div = soup.select_one("#content")
has_data_attr = 'data' in content_div.attrs
print('是否有 data 属性:', has_data_attr)
has_href_attr = 'href' in content_div.attrs
print('是否有 href 属性:', has_href_attr)
执行结果:
是否有 data 属性: True
是否有 href 属性: False
示例:修改属性值
from bs4 import BeautifulSoup
html_content = '''
<div id="content" data="你好">测试01</div>
<div>测试03</div>
'''.strip()
soup = BeautifulSoup(html_content, 'html.parser')
print('------处理前-----')
print(soup)
print('------修改 data 属性-----')
content_div = soup.select_one("#content")
print('当前data 属性:', content_div.attrs['data'])
content_div.attrs['data'] = 'zz'
print('------处理后-----')
print(soup)
执行结果:
------处理前-----
<div data="你好" id="content">测试01</div>
<div>测试03</div>
------修改 data 属性-----
当前data 属性: 你好
------处理后-----
<div data="zz" id="content">测试01</div>
<div>测试03</div>
示例:添加属性值
from bs4 import BeautifulSoup
html_content = '''
<div id="content" data="你好">测试01</div>
<div>测试03</div>
'''.strip()
soup = BeautifulSoup(html_content, 'html.parser')
print('------处理前-----')
print(soup)
print('------添加 data 属性-----')
content_div = soup.select_one("#content")
content_div.attrs['data2'] = 'zz'
print('------处理后-----')
print(soup)
执行结果:
------处理前-----
<div data="你好" id="content">测试01</div>
<div>测试03</div>
------添加 data 属性-----
------处理后-----
<div data="你好" data2="zz" id="content">测试01</div>
<div>测试03</div>
示例:删除属性值
from bs4 import BeautifulSoup
html_content = '''
<div id="content" data="你好">测试01</div>
<div>测试03</div>
'''.strip()
soup = BeautifulSoup(html_content, 'html.parser')
print('------处理前-----')
print(soup)
print('------删除 data 属性-----')
content_div = soup.select_one("#content")
del content_div.attrs['data']
print('------处理后-----')
print(soup)
执行结果:
------处理前-----
<div data="你好" id="content">测试01</div>
<div>测试03</div>
------删除 data 属性-----
------处理后-----
<div id="content">测试01</div>
<div>测试03</div>