#beautifulsoup是Python的一个第三方库,用来解析html #Xpath的解析速度更快,xpath底层是c from bs4 import BeautifulSoup #BeautifulSoup里面需要两个参数,一个是open方法,一个是固定写法‘lxml’ #open里面有两个参数:一个是想要解析的数据,另一个是编码格式 #BeautifulSoup转化数据(bs)为类对象 bs=BeautifulSoup(open('H5文件.html',encoding='utf-8'),'lxml') # print(bs) # print(type(bs)) # #bs.XX获取XX当中的第一个XX以及第一个XX里面的内容 # print(bs.title)#获取网页中的title标签 # print(bs.head)#获取head标签以及head内部的其他标签 # print(bs.a)#获取网页中的第一个a标签 # print(bs.name)#获取当前内容的标签名、、bs表示的是一个整体 # print(bs.head.name)#获取head的标签名 # print(bs.title.name)#获取title的标签名 # print(bs.a.attrs)#attribute属性 获取指定标签的所有属性,如果没有做有特别处理,bs.XX第一个XX # print(bs.p['class'])#html中的id是唯一的,标签和class是多对多,一对多等的关系 # print(bs.html['lang']) # print(bs.a) # del bs.a['href'] # print(bs.a) # print(bs.a.string)#获取制定标签的文本内容 # print(bs.div.string)#string获取的文本指的是本标签的文本,不包含子标签的文本 # print(bs.head.contents)#遍历 # print(bs.body.contents)#contents 可以获取制定标签下的所有内容 # print(bs.div.contents[3])#获取指定内容的索引的内容 # print(bs.title.parent) #parent 父级。输出上级标签以及其中全部标签 # res=bs.find_all('a') # print(res) # for value in res: # print(value) # print(bs.find(id="jd")) # 找出符合的第一条 # print(bs.find_all(class_='shopping')) #找出所有符合条件的 # print(bs.select('a'))#选择指定的标签 # print(bs.select('.first')) #选择所有类名为first # print(bs.select('#jd')) print(bs.select('div.now')) #找到一个类名为now的标签
<!DOCTYPE html>
<html lang="en">
<head>
<!--<meta charset="UTF-8">-->
<title>Title</title>
</head>
<body>
<ul>
<li>啤酒</li>
<li>饮料</li>
<li>矿泉水</li>
<a href="#">shiam</a>
<li><a href="http://www.baidu.com">是的</a></li>
</ul>
<p class="first">first_people</p>
<p id="one">
<span>
hello word
</span>
</p>
<p class="first second" id="two">second</p>
<div class="now">
<p id="jd" class="third"> third909 </p>
<a id="jdd" href="https://www.meishij.net"></a>
<a class="shopping" href="">我是JD</a>
</div>
</body>
</html>