BeautifulSoup4攻略
作者:互联网
prettify() 格式化输出标准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>
"""
from bs4 import BeautifulSoup
#import re
soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.prettify())
输出为
提取标签及标签名字
提取所有的a标签或者p标签,然后在提取属性
代码:
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>
"""
from bs4 import BeautifulSoup
import re
soup = BeautifulSoup(html_doc, 'html.parser')
# 提取标签以及标签名
print(soup.title,'\n',soup.a)# 提取a标签及title标签
# 提取标签名字
print(soup.title.name,'\n',soup.a.name)
print(soup.p)
# 提取标签对应属性的属性值
print(soup.p['class'],'p的属性值')
# 以上都只能提取单个标签
# 现在学习一次提取多个标签
print(soup.p)
print(soup.find_all('a'))
# 寻找a标签所有的链接
for i in soup.find_all('a'):
print(i['href'])
输出为 :
标签:提取,标签,soup,html,攻略,doc,print,BeautifulSoup4 来源: https://www.cnblogs.com/hmhql/p/13703518.html