文件樹 節點內容

2021-10-23 05:49:28 字數 1696 閱讀 3372

本文此次分享運用beautifulsoup獲取節點內容。

import requests#爬蟲庫

from bs4 import beautifulsoup#解析庫

headers=

url=requests.get(

'',headers=headers)

html=url.text

soup=beautifulsoup(html,

'lxml'

)#直接子節點

print

(soup.head.contents)

#將head的所有子代節點以列表形式輸出。

print

(soup.head.children)

#也是輸出head的所有子節點,但是可以通過for迴圈輸出

for child in soup.head.children:

print

(child)

#所有子孫節點,通過for迴圈全部讀取出來

print

(soup.head.descendants)

for child in soup.head.descendants:

print

(child)

string是beautifulsoup中用來獲取節點內容的板塊,但是string在使用時必須注意該標籤內不能有多個子節點,只能篩選單個子節點。還有就是空格和換行都算乙個節點,會影響到string的使用,所以最好使用.text來獲取文字。

獲取乙個tag下多個內容:運用.strings或者.stripped_strings(可以除去多多餘空白內容),仍需要使用for迴圈進行輸出。

for string in soup.head.strings:

print

(string)

for string in soup.head.stripped_strings:

print

(string)

.parent可以獲得當前tag的父節點;.parents可以獲得當前元素的所有父節點

print

(soup.head.parent.name)

.next_sibling獲取下乙個兄弟節點

.prev_sibling獲取上乙個兄弟節點

前後節點:該節點之前(後)的所有節點,不分層次,可以找到父輩或其他不同層次的節點,與兄弟節點只能找到同一層次的不同。

.next_element

.previous_element

.next_elements

.previous_elements

find_all 可以獲得當前tag的所有tag子節點

print

(soup.find_all(

'a')

)#獲取所有a標籤

#補充:可以填兩個標籤形式的列表['a','b']獲取a,b標籤;

#true,找出所有子節點

#正規表示式

find_all(標籤內屬性名=屬性值)

print

(soup.find_all(class_=

'summary-text'

))

文件樹(節點樹)

hello world 上面所有的節點彼此間都存在關係。除文件節點之外的每個節點都有父節點。舉例,和 的父節點是 節點,文字節點 hello world 的父節點是 節點。大部分元素節點都有子節點。比方說,節點有乙個子節點 節點。節點也有乙個子節點 文字節點 dom tutorial 當節點分享同乙...

GPMC裝置樹節點屬性編寫參考文件翻譯

閱讀linux核心目錄下的裝置樹編寫參考文件,為便於日後查閱,將內容進行了翻譯,如下。在裝置樹檔案中配置gpmc節點時需要根據各屬性的含義配置引數。時序參見手冊 am572x sitara processor technical reference manual rev.k pdf page3572...

extjs 樹節點操作

tree 樹 node 節點 1 全部展開 tree.expandall 2 全部收縮 tree.collapseall 3 得到父節點 node.parentnode 4 判斷是否有父節點 node.parentnode null 5 判斷是否有子節點 node.haschildnodes 6 獲...