BeautifulSoup庫的使用

2021-09-26 06:53:39 字數 2974 閱讀 7871

五.總結

from bs4 import beautifulsoup

# 例項化bs4物件

soup = beautifulsoup(res.text,

'lxml'

)# bs4解析出來的結果會是乙個列表

tag = soup.select(

"css選擇器表示式"

)

# css選擇器:

1.根據節點名及節點層次關係定位標籤: 標籤選擇器 & 層級選擇器

soup.select(

'title'

)soup.select(

'div > ul > li'

)# 單層級選擇器

soup.select(

'div li'

)# 多層級選擇器

2.根據節點的class屬性定位標籤:

class選擇器

soup.select(

'.panel')3

.根據id屬性定位標籤:

id選擇器

soup.select(

'#item')4

.巢狀選擇: 對解析的結果再次進行解析

ul_list = soup.select(

'ul'

)for ul in ul_list:

print

(ul.select(

'li'))

# 獲取節點的文字或屬性:

# tag_obj是解析後賦值的變數

tag_obj.string: 獲取直接子文字-

->如果節點內有與直系文字平行的節點, 該方法拿到的是none

tag_obj.get_text(

): 獲取子孫節點的所有文字

tag_obj[

'attribute'

]: 獲取節點屬性

今天要爬取的頁面是詩詞名句網中的**《三國演義》

確認url, 我們首先要對**的列表頁進行爬取

列表頁鏈結

分析列表頁, 從列表頁中拿取詳情頁的鏈結

對詳情頁的位址進行拼接, 同時請求詳情頁

對詳情頁面的響應進行解析

寫入檔案

import time

import requests

from bs4 import beautifulsoup

# 構造儲存**的路徑, 需要自己先建立乙個資料夾

fiction_path =

"./fictions/"

defspider_fiction()

:"""

1.爬取三國演義

"""start_time = time.time(

) url =

''# 定製請求頭資訊

headers =

# 使用當前位址去請求,獲取響應到的列表頁

response_list_page = requests.get(url=url, headers=headers)

# 對響應到的列表頁進行解析,使用lxml解析器

soup = beautifulsoup(response_list_page.text,

'lxml'

)# 進行解析獲取所有的回合超連結, 超連結都在a標籤內

a_list = soup.select(

'.book-mulu ul li a'

)for a in a_list:

# 下面只有子節點, 所以使用string

name = a.string

# 獲取詳情頁位址的同時將位址拼接

href =

''+ a[

'href'

]# 使用獲取到的href來訪問詳情頁

response_detail_page = requests.get(url=href, headers=headers)

# 獲取到詳情頁的資料首先需要根據資料例項化beautifulsoup類

soup_detail = beautifulsoup(response_detail_page.text,

'lxml'

)# 使用例項化的物件來進行資料解析

p_list = soup_detail.select(

'.chapter_content p'

)# 獲取到一回合的所有內容後需要將資料正常寫入到檔案內

with

open

(fiction_path + name +

'.txt'

,'w'

, encoding=

'utf-8'

)as f:

# 因為解析出來的資料是乙個列表,所以要迴圈遍歷

for p in p_list:

# python2中的寫入檔案方法,在python3需要加上file=檔案控制代碼,print自帶換行

print

(p.string,

file

=f)# 或者使用write

# f.write(p.string + "\n")

end_time = time.time(

)# 測試寫入檔案總用時時間

print

(end_time-start_time)

if __name__ ==

'__main__'

: spider_fiction(

)

bs4是純python編寫的解析庫, 解析速度相對於xpath來說要慢(xpath底層是c編寫的), 所以還是推薦大家使用xpath, 不過bs4最好也要會使用.

xpath解析的文章

BeautifulSoup庫的使用

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

BeautifulSoup庫的使用

beautifulsoup 解析庫解析器 使用方法 python標準庫 beautifulsoup markup,html.parser lxml html解析器 beautifulsoup markup,lxml lxml xml解析器 beautifulsoup markup,xml html5...

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