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"]')