在爬取网页的时候,爬下的数据需要解析html。如下代码。
使用python3.x
from bs4 import BeautifulSoup as bs
html = '''<html>
<head>
<title class='ceshi'>super 哈哈 star</title>
</head>
<body>
天下第一帅
<p class='sister'>
是不是
</p>
<p id='seeyou'>haha嘻嘻</p>
</body>
</html>'''
str = '''用BeautifulSoup解析数据 python3 必须传入参数二'html.parser' 得到一个对象,接下来获取对象的相关属性'''
html = bs(html, 'html.parser')
# 读取title内容
print(html.title)
attrs = html.title.attrs
print(attrs)
print(attrs['class'][0]) # 显示class里面的内容
print(html.body) # 显示body内容
print(html.p.attrs)
print(html.select("#seeyou")[0].string) # 解析id是seeyou的标签里面的内容
文章来源—-渴望飞的鱼