BeautifulSoup庫的使用

2022-02-06 06:36:12 字數 1553 閱讀 9606

beautifulsoup

解析庫解析器

使用方法

python標準庫

beautifulsoup(markup,"html.parser")

lxml html解析器

beautifulsoup(markup,"lxml")

lxml xml解析器

beautifulsoup(markup,"xml")

html5lib

beautifulsoup(markup,"html5lib")

基本使用

html ="""

liudemeng -

標籤選擇器

選擇元素

html ="""

liudemeng -

獲取名稱

html ="""

liudemeng -

獲取內容

html ="""

liudemeng -

獲取內容

html ="""

liudemeng -

巢狀選擇

html ="""

liudemeng -

子節點和子孫節點

"""from bs4 import beautifulsoup

soup = beautifulsoup(html, 'lxml')

print(soup.div.contents)

"""from bs4 import beautifulsoup

soup = beautifulsoup(html, 'lxml')

print(soup.div.children)

for i, child in enumerate(soup.div.children):

print(i, child)

父節點和祖先節點

html ="""

liudemeng -

兄弟節點

html ="""

liudemeng -

標準選擇器

find_all(name, attrs, recursive,text,**kwargs)

可根據標籤名.屬性.內容查詢文件

name

html ="""

liudemeng -

attrs

html ="""

liudemeng -

text

html ="""

liudemeng -

find(name, attrs, recursive,text,**kwargs)

find返回單個元素,find_all返回所有的元素

find_parents() 和 find_parent()

find_parents() 返回所有的父節點, find_parent()返回父節點

總結:

BeautifulSoup庫的使用

解析器 使用方法 優勢劣勢 python標準庫 beautifulsoup markup,html.parser python的內建標準庫 執行速度適中 文件容錯能力強 python 2.7.3 or 3.2.2 前的版本中文容錯能力差 lxml html 解析器 beautifulsoup mar...

BeautifulSoup庫的使用

五.總結 from bs4 import beautifulsoup 例項化bs4物件 soup beautifulsoup res.text,lxml bs4解析出來的結果會是乙個列表 tag soup.select css選擇器表示式 css選擇器 1.根據節點名及節點層次關係定位標籤 標籤選擇...

beautifulSoup庫的使用案例

from urllib.request import urlopen from bs4 import beautifulsoup url html urlopen url bs beautifulsoup html,html.parser for child in bs.find table chi...