BeautifulSoup隨筆

Learn BeautifulSoup

BeautifulSoup用法

引用崔慶才 靜覓

基本語法及用法

初始化

soup = BeautifulSoup(html, 'lxml') (or BeautifelSoup(open(filename), 'lxml') )

四大對象種類

* Tag
    * 即標簽 如soup.[title| head| a| p| 等等]
    * name: soup.name, soup.head.name
    * attrs 
* NavigableString
    * soup.p.string返回標簽內(nèi)容
* BeatifulSoup
* Commit

遍歷

* 直接子節(jié)點 .contents .children
* 所有子孫節(jié)點 .descendants
* 父節(jié)點 .parent .parents
* 兄弟節(jié)點 .next_sibling .privious_sibling
* 節(jié)點內(nèi)容 .string
* 多個內(nèi)容 .string .stripped_strings

搜索文檔樹

* find_all(name, attrs, recursive, text, **kwargs)
    * name: 標簽名為name 
        * 字符串
        * 正則表達式
        * 列表
        * True
        * 方法
    * kwargs: 。。。
    * text: 即查找文本內(nèi)容
    * limit參數(shù): 限制返回結(jié)果數(shù)量
    * recursive: 限制搜索節(jié)點是否需要子孫節(jié)點
* 另外方法有 find find_parent, find_all_next等等

CSS選擇器

> select方法是很常用的
  • 通過標簽 soup.select('title')
  • 通過類名 soup.select('.content')
  • 通過id soup.select('#link1')
  • 屬性查找 soup.select('div [class="content"]')
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容