python爬蟲日誌(7)BeautifulSoup

BeautifulSoup解析網頁其實是將網頁個標籤及內容存放在一個樹結構中,每一個標籤是一個結點,字符串自身是一個結點沒有子節點,標籤的屬性會是它的子節點。soup.prettify()能夠將網頁代碼以一種更優美的結構展示出來。html

經常使用到須要掌握的內容有以下這些:python

soup.title#獲取名爲title的標籤的內容
soup.tag.name #獲取標籤的名字
soup.tag.string #獲取標籤的文本內容
soup.tag #直接訪問標籤內容
soup.tag.['attribute'] #獲取標籤的屬性 如class,id等等
soup.find('a') #找到第一個符合條件的內容
soup.find_all('a','link3')  #找到全部符合條件的內容,能夠找標籤,也能夠加上屬性來篩選,也能夠只寫屬性,不寫標籤,如soup.find(id='link3')
soup.get_text()  #用於獲取全部文字內容
tag.attrs #獲取標籤的屬性,有的標籤有多值屬性
tag.string.replace_with('') #能夠將字符串內容用參數替換
tag.contents #能夠將子節點以列表的方式輸出
tag.children #能夠對子節點進行循環 for child in tag.children: print(child)
#.contents和.children屬性僅包含tag的直接子節點,.descendants則能夠對tag全部子孫結點進行遞歸循環
#.strings若是tag中有多個字符串,能夠用.strings來循環獲取
#.stripped_strings能夠將字符串的首尾字符串中間的空符去掉
#.parent能夠獲取父節點
#.next_sibling和.previous_sibling能夠獲取元素的下一個或前一個兄弟結點
#Tag,NavigableString,BeautifulSoup,comment html和xml中的四大類

更多詳細內容可查詢beautifulsoup文檔https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/ ,http://beautifulsoup.readthedocs.io/zh_CN/latest/,分別爲4.2和4.4的文檔code

相關文章
相關標籤/搜索