简单使用
from bs4 import BeautifulSoup
import doc_html
soup = BeautifulSoup(doc_html.html_doc, "html.parser")
# input标签
print("-----input-----")
print(soup.input.attrs)
print(soup.input.attrs['style'])
print(soup.input.has_attr('type'))
# p标签
print("-----p-----")
print(soup.p)
# 获取第一个p标签下的所有的子结点
print(type(soup.p.children))
print(list(soup.p.children)[0])
print(list(soup.p.children)[0].text)
# 指定查找
print("-----指定查找-----")
print(soup.find_all("p"))
print(soup.find(type="text"))
print(soup.find(id="btt"))
# 找到所有满足条件的(集合)
print(soup.select(".first-2"))
print(soup.select("#btt"))
print(soup.select(".first-2 p"))
输出(从input开始)
-----input-----
{'type': 'text', 'style': 'background-color: transparent; border:0px;'}
background-color: transparent; border:0px;
True
-----p-----
<p><span>这是个盒子模型,运用了HTML和CSS的知识创建,里面含有很多其他知识,比如对图像的理解,页面设计等。
这些知识想要掌握好,需要经过很久的训练,对各种标签和属性都了解</span>
<span>第二个了</span>
</p>
<class 'list_iterator'>
<span>这是个盒子模型,运用了HTML和CSS的知识创建,里面含有很多其他知识,比如对图像的理解,页面设计等。
这些知识想要掌握好,需要经过很久的训练,对各种标签和属性都了解</span>
这是个盒子模型,运用了HTML和CSS的知识创建,里面含有很多其他知识,比如对图像的理解,页面设计等。
这些知识想要掌握好,需要经过很久的训练,对各种标签和属性都了解
-----指定查找-----
[<p><span>这是个盒子模型,运用了HTML和CSS的知识创建,里面含有很多其他知识,比如对图像的理解,页面设计等。
这些知识想要掌握好,需要经过很久的训练,对各种标签和属性都了解</span>
<span>第二个了</span>
</p>, <p>这是一个用来判断是否是透明色的盒子</p>]
<input style="background-color: transparent; border:0px;" type="text"/>
<h2 id="btt">这是一个标题</h2>
[<div class="first-2">
<h2>这里可能用来有透明色</h2>
<p>这是一个用来判断是否是透明色的盒子</p>
</div>, <div class="first-2">
<button onclick="btn()">点击!</button>
<h2 id="btt">这是一个标题</h2>
</div>]
[<h2 id="btt">这是一个标题</h2>]
[<p>这是一个用来判断是否是透明色的盒子</p>]
使用lxml解析器
from bs4 import BeautifulSoup
from lxml import etree
import doc_html
soup = BeautifulSoup(doc_html.html_doc, "lxml")
print(soup.input)