BeautifulSoup學習筆記

2021-10-12 16:18:57 字數 2248 閱讀 5662

# -*- coding:utf-8 -*-

import requests

from bs4 import beautifulsoup

# 發出請求獲得html原始碼的函式

defget_html

(url)

:# 偽裝成瀏覽器訪問

headers =

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

.text

return resp

# 解析頁面,獲得資料資訊

defhtml_parse()

:# 呼叫函式,for迴圈迭代出所有頁面

for url in all_page():

# beautifulsoup的解析

soup = beautifulsoup(get_html(url)

,'lxml'

)# 書名

alldiv = soup.find_all(

'div'

, class_=

'pl2'

) names =

[a.find(

'a')

['title'

]for a in alldiv]

# 作者

allp = soup.find_all(

'p', class_=

'pl'

) authors =

[p.get_text(

)for p in allp]

# 評分

starspan = soup.find_all(

'span'

, class_=

'rating_nums'

) scores =

[s.get_text(

)for s in starspan]

# 簡介

sumspan = soup.find_all(

'span'

, class_=

'inq'

) sums =

[i.get_text(

)for i in sumspan]

#原文摘錄

# excerpts_list = soup.find_all('li', class_='hd')

# excerpts = [m.get_text() for m in excerpts_list]

for name, author, score,

sumin

zip(names, authors, scores, sums)

: name =

'書名:'

+str

(name)

+'\n'

author =

+str

(author)

+'\n'

score =

'評分:'

+str

(score)

+'\n'

sum=

'簡介:'

+str

(sum)+

'\n'

# excerpt = '原文摘錄:' + str(excerpt) + '\n'

data = name + author + score +

sum# 儲存資料

# f.writelines(data + '********************===' + '\n')

print

(data)

# 獲得所有頁面的函式

defall_page()

: base_url =

''urllist =

# 從0到225,間隔25的陣列

for page in

range(0

,50,25

):allurl = base_url +

str(page)

return urllist

# # 檔名

# filename = '豆瓣圖書top250.txt'

# # 儲存檔案操作

# f = open(filename, 'w', encoding='utf-8')

# # 呼叫函式

# html_parse()

# f.close()

# print('儲存成功。')

html_parse(

)

BeautifulSoup學習筆記

prettify 將html 格式化 get text 獲得所有文字內容 contens 返回所有子節點 children 返回子節點生成器 descendants 返回所有子孫節點的生成器 strings 返回包含的多個字串的生成器 stripped strings 返回包含的多個字串 去除多餘空...

學習日記 使用BeautifulSoup爬取小說

半個月前入坑了python,近幾天看到csdn上有一些關於美麗的湯 beautifulsoup 的介紹和使用方法,於是自己也試著寫了乙個爬蟲。小白的學習日記,若有不當之處,歡迎大神們指點!使用python版本 python3.8 隨便在網上搜了個 試著爬下來。鏈結 檢視網頁的源 發現文章內容都是p標...

bs4 beautifulsoup學習筆記

todo 用requests庫獲取網頁html r requests.get demo r.text對demo進行html的解析 soup beautifulsoup demo,html.parser 格式化html列印出來 print print soup.prettify 列印title標籤 p...