大家好,上篇推文介绍了BeautifulSoup抓取的一些基础用法,本篇内容主要是介绍BeautifulSoup模块的文档树使用以及实例。
一、遍历文档树
直接看代码吧
from bs4 import BeautifulSoup
html='<html> <head> <meta content="text/html;charset=utf-8" http-equiv="content-type"/> <meta content="IE=Edge" http-equiv="X-UA-Compatible"/> <meta content="always" name="referrer"/> <title> python 知识学堂 </title> </head> <body > <div id="wrapper"> <div id="head"> <div class="head_wrapper"> <div class="s_form"> <div class="s_form_wrapper"> <div id="lg"> <img height="129" hidefocus="true" src="/bd_logo1.png" width="270"/> </div> <form action="/" class="form" id="form" name="fm"> <span class="bg s_ipt_wr"> <input autocomplete="off" autofocus="autofocus" class="keyword" id="kw" maxlength="255" name="wd" value=""/> </span> <span class="bg s_btn_wr"> <input autofocus="" class="bg s_btn" id="su" type="submit" value="搜索"/> </span> </form> </div> </div> <div id="u1"> <a class="mnav" href="/link_1" > Python</a> <a class="mnav" href="/link_2" > 知识 </a> <a class="mnav" href="/link_3"> 学堂 </a> <a class="mnav" href="/link_4" > 欢迎 </a> <a class="mnav" href="/link_5"> 您 </a> </div> </div> </div> </div> </body> </html>'
#上面是随便写的一个页面代码
soup=BeautifulSoup(html,'lxml')
#print(soup.prettify())
print("-------------------------------------------------分割符----------------------------------------------------")
print(soup.head) # 获取head 标签
print("-------------------------------------------------分割符----------------------------------------------------")
print(soup.a) #获取a 标签 默认是第一个
print("-------------------------------------------------分割符----------------------------------------------------")
print('contents:')
print(soup.a.contents) #tag的 .contents 属性可以将tag的子节点以列表的方式输出
print("-------------------------------------------------分割符----------------------------------------------------")
print('children:')
for child in soup.form.children: #获取标签下的一级子标签
print(child)
print("-------------------------------------------------分割符----------------------------------------------------")
print('descendants:')
for child in soup.form.descendants: #获取标签下的所有tag子孙节点进行递归循环
print(child)
print("-------------------------------------------------分割符----------------------------------------------------")
print('strings:')
for str in soup.strings: #输入标签内的字符串
print(str)
print("-------------------------------------------------分割符----------------------------------------------------")
print('stripped_strings:')
for str in soup.stripped_strings: #输入标签内的字符串 去除空字符串