1. 程式人生 > >beautifulSoup20%基礎知識

beautifulSoup20%基礎知識

詳細的內容請看這裡——參考部落格,下面是自己需要參考的部分總結。

  1. 建立 Beautiful Soup 物件,首先必須要匯入 bs4 庫
from bs4 import BeautifulSoup
  1. 建立一個字串,請將字串拷貝出來,再參考後面的例子,這樣才能明白。
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"
>
<b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>, <a href="http://example.com/lacie" class="sister" id="link2"
>
Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """
  1. 建立 beautifulsoup 物件
soup = BeautifulSoup(html)
  1. Beautiful Soup將複雜HTML文件轉換成一個複雜的樹形結構,每個節點都是Python物件,所有物件可以歸納為4種:Tag、NavigableString、BeautifulSoup、Comment。

(1) Tag:Tag 是什麼?通俗點講就是 HTML 中的一個個標籤,例如head,title,a,p等,註釋為輸出。

print soup.title
#<title>The Dormouse's story</title>
print soup.head
#<head><title>The Dormouse's story</title></head>
print soup.a
#<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>
print soup.p
#<p class="title" name="dromouse"><b>The Dormouse's story</b></p>

它有兩個屬性,name和attrs,使用如下。

#name到沒什麼,主要在sttrs。
print soup.name #[document]
print soup.head.name #head

print soup.p.attrs
#{'class': ['title'], 'name': 'dromouse'}
print soup.p['class'] #['title']

(2)NavigableString:獲取標籤內的字串。

print soup.p.string
#The Dormouse's story

(3)BeautifulSoup:
(4)Comment

  1. 遍歷文件樹,.contents .children 屬性。
print soup.head.contents 
#[<title>The Dormouse's story</title>]
print soup.head.contents[0]#會以列表的形式出書。
#<title>The Dormouse's story</title>
  1. CSS選擇器,我們在寫 CSS 時,標籤名不加任何修飾,類名前加點,id名前加 #,在這裡我們也可以利用類似的方法來篩選元素,用到的方法是 soup.select(),返回型別是 list。
print soup.select('title') 
#[<title>The Dormouse's story</title>]
print soup.select('a')
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

print soup.select('.sister')#通過類名查詢
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

print soup.select('#link1')#通過id查詢
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

#組合查詢,二者需要用空格分開
print soup.select('p #link1')
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]
print soup.select("head > title")
#[<title>The Dormouse's story</title>]

#屬性查詢,屬性需要用中括號括起來,注意屬性和標籤屬於同一節點,所以中間不能加空格,
print soup.select('p a[href="http://example.com/elsie"]')
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]