1. 程式人生 > >python:BeautifulSoup select()/select_one() 用法總結

python:BeautifulSoup select()/select_one() 用法總結

BeautifulSoup select()/select_one() 用法總結:

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><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> """

使用 select()/select_one() 時,標籤名不加任何修飾,類名前加點,id名前加 #,屬性用 [屬性=’xxxx’]。
select() 返回型別是 list。
select_one() 返回值是list的首個。

設定字符集,匯入包

# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup as bs

(1)通過標籤名查詢

link_node = soup.select_one('a')
print('通過標籤查標籤名:   '+link_node.name)
#通過標籤查標籤名:   a
print(soup.select('b')) #[<b>The Dormouse's story</b>]

(2)通過類名查詢

link_node = soup.select_one('.sister')
print('通過class查href:   '+link_node.get('href'))
#通過class查href:   http://example.com/elsie

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>]

結果為一個list,如果需要取出裡面元素資訊,需要用 for 迴圈

(3)通過 id 名查詢

link_node = soup.select_one('#link1')
print('通過id查內容:   '+link_node.text)
#通過id查內容:   Elsie

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

(4)組合查詢
查詢 p 標籤中,id 等於 link1的內容,二者需要用空格分開

link_node = soup.select_one('p #link1')
print(link_node)
#<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>

#獲取結果中的class
print(link_node.get('class'))
#['sister']
#這裡注意,獲取class返回是個list,其他的均為str、int

#獲取結果中的href
print(link_node.get('href'))
#http://example.com/elsie

直接子標籤查詢
print soup.select("head > title")
#[<title>The Dormouse's story</title>]

(5)屬性查詢
查詢可以加入屬性元素,屬性需要用中括號括起來,注意屬性和標籤屬於同一節點,所以中間不能加空格,否則會無法匹配到。

#查a標籤下 帶有屬性為http://example.com/tillie的結果,注意,這裡是同一個節點
link_node = soup.select_one('a[href="http://example.com/tillie"]')
print('通過組合標籤和屬性查詢內容:   '+link_node.text)
#通過組合標籤和屬性查詢內容:   Tillie

#p標籤下 帶有href屬性為http://example.com/tillie的結果,注意,這裡是子節點
link_node = soup.select_one('p [href="http://example.com/tillie"]')
print(link_node.text)
#Tillie