得到HTML
html = urlopen('http://example.com')
得到 BeautifulSoup對象 (完整的DOM Tree)
bsObj = BeautifulSoup(html.read) #過期
bsObj = BeautifulSoup(html,'html.parser',from_encoding='utf8') #新標準(參數三非必須)
得到 Tag對象 (能夠一直點下去)
#最好使用try包圍起來,不然讀到不存在的標籤會報錯
body = bsObj.body //title包含tag之間的全部內容
find 和 find_all ( 能夠使用以上兩種對象 )
findAll(tag, attributes, recursive, text, limit, keywords)
#標籤名 用於匹配的字典 是否迭代(默認是) 使用text = '關鍵字'匹配,無需參數12 限制前n項 keyword 是冗餘設計,至關於bsObj.findAll("", {"id":"text"})
find(tag, attributes, recursive, text, keywords)
查找標籤(對於Python中的關鍵字,如:class 能夠使用 class_ 或者 'class')
# <span class="red">
nameList = bsObj.find_all(name='span', attrs={
'class': 'red'}) # 獲得的是一個bs4的自定義對象[<span class="red"> 我是中間的文字1 </span>, <span class="red"> 我是中間的文字2 </span>]
for name in nameList:
print(name.get_text()) # 得到標籤間的內容
print('-------------------')
子,後代,兄弟標籤(使用find會捨得代碼更健壯,此處僅爲展現家族關係)
# 子標籤
for child in bsObj.children:
print(child)
# 後代標籤
for descendant in bsObj.descendants:
print(descendant)、
# 兄弟標籤 next_sibling previous_sibling 一個;next_siblings previous_siblings 一組
for next_sibling in bsObj.body.h1.next_siblings:
print(next_sibling)
# 父標籤 parent 和 parents
for parent in bsObj.body.h1.parents:
print('===========')
print(parent)
正則表達式(能夠在任何一個須要參數的地方傳遞正則)
bsObj.find_all(re.compile('<span class="red">'))
images = bsObj.findAll("img",{"src":re.compile("\.\.\/img\/gifts/img.*\.jpg")})
獲取 Tag 的屬性
myTag.attrs