1,BeautifulSoup庫是解析,遍歷,維護“標簽樹”代碼的功能庫;名字為beautifulsoup4或bs4;
引用方式為:from bs4 import BeautifulSoup 或者 import bs4;
1.1 BeautifulSoup類的五種基本元素:
1.1.1 Tag標簽:<p class="title"> ... </p> ;
意義:最基本的信息組織單元,標簽總是成對出現,標簽頭常包含有該標簽的多對屬性(attributes);
引用格式:對象.標簽名字;
格式意義:表示返回標簽名字為name的bs4類對象的標簽全部內容;
以下四種屬性都是tag標簽基礎上的衍生屬性(便於理解這么記,語法上可能不成立);
1.1.2 Name 標簽名字:<p>...</p>
意義:標簽的名字為p;
引用格式:對象.標簽名字.name;
格式意義:表示返回該標簽的名字;
1.1.3 Attributes 標簽屬性,
<p class="title"><b>The demo python introduces several python courses.</b></p>
意義:class="title"為標簽的類屬性;
引用格式:對象.標簽名字.attrs['class'];
格式意義:返回該標簽屬性的字典形式(包含該標簽的所有屬性);若是加上后綴中括號,表示返回中括號內 特定類的屬性值,此處應返回'title';
1.1.4 NavigableString 標簽內非屬性字符串(...內容部分);
格式:對象.標簽名字.string;
格式意義:返回該標簽的內容部分;如1.1.3例中的灰色部分;
1.1.5 Comment 標簽內字符串的注釋部分,一種特殊的Comment類型;
格式:以 <! 開頭表示注釋;我們在提取內容的時候要注意和NavigableString內容進行類型的區分;
格式意義:(以后理解了補充)
import requests from bs4 import BeautifulSoup r=requests.get("http://www.python123.io/ws/demo.html") demo=r.text soup=BeautifulSoup(demo,'html.parser') soup.prettify() print(soup.title) print(soup.title.name) print(soup.title.parent.name) print(soup.p.attrs) print(soup.title.string) <title>This is a python demo page</title> title head {'class': ['title']} This is a python demo page
1.2 beautifulsoup庫的解析語法:
1.2.1 soup=BeautifulSoup('<name>...data...</name>','html.parser')
該函數表示以‘html.parser’的方式將'data'解析成BeautifulSoup類,存入對象soup中;
1.2.2 soup.prettify()
該函數為HTML文本對象soup增加\n,提高文本的可讀性;
1.2.3 bs4庫默認將HTML文本以utf-8編碼解析,Python3.x也是;
1.2.4 type()
可以返回標簽的類型,或者標簽屬性的類型;
2, bs4庫的遍歷方法:
2.0 迭代類型:迭代類型只能用在for和in循壞語句中;
2.1 下行遍歷:
2.1.1 .contents :返回所有子節點的節點信息存入列表;'\n'屬於一個子節點;
2.1.2 .children: 用於循環遍歷子節點;迭代類型;用法舉例如下:
for child in soup.body.children: print(child)
2.1.3 .descendants: 用於循環遍歷所有子孫節點;迭代類型;用法舉例如下:
#先打印body的子節點p,接着打印p的子節點b,然后打印b的內容字符串;
#在遍歷的時候可以把標簽,標簽內容,NavigitableString內容,換行符,都視為節點;因為都會遍歷;
for child in soup.body.descendants: print(child)
2.2 上行遍歷:
2.2.1 .parent : 返回父節點的標簽;
2.2.2 .parents : 返回父節點以及先輩節點的標簽;
2.2.3 我們在上行遍歷parents的時候會遍歷到對象本身,但是對象本身是不具有標簽的,建議加上判斷語句區分;
2.3 平行遍歷:(不同父節點下的平行節點不能平行遍歷)
2.3.1 .next_sibling : 返回當前節點的下一平行節點;標簽之間的NavigableString內容也是節點;
2.3.2 .previous_sibling: 返回當前節點的上一平行節點;
2.3.3 .next_siblings: 用於循壞遍歷當前節點的后續平行節點;迭代類型;
for sibling in soup.a.next_siblings: print(sibling)
2.3.4 .previous_siblings:用於循壞遍歷當前節點的前續平行節點;迭代類型;
for sibling in soup.a.previous_siblings: print(sibling)