Python數(shù)據(jù)解析bs4庫使用BeautifulSoup方法示例
更新時間:2023年08月21日 09:59:25 作者:YiYa_咿呀
這篇文章主要為大家介紹了Python數(shù)據(jù)解析bs4庫使用BeautifulSoup方法示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
1. 安裝bs4庫
pip install bs4
2. 使用beautiful soup
用法如下:
find_all:find_all找到所有符合條件的節(jié)點
find:find指的是找第一個符合條件的節(jié)點
calss_:因為和python中的關鍵字class重合,因此在后面加個_加以區(qū)分
attrs={"":""}:attrs的對象存儲條件,此時的class無需加_
import requests from bs4 import BeautifulSoup import re url = "http://www.crazyant.net/" r = requests.get(url) if r.status_code != 200: raise Exception() html_doc = r.text # 創(chuàng)建beautiful soup,將爬取的內容通過BeautifulSoup解析,這里告訴BeautifulSoup這個是爬取到的html頁面,默認也是這個,但是會發(fā)出警告 soup = BeautifulSoup(html_doc,"html.parser") # find_all找到所有符合條件的節(jié)點,find指的是找第一個 h2_nodes = soup.find_all("h2",class_="entry-title")
3. 使用bs4爬取優(yōu)美圖庫的圖片
from bs4 import BeautifulSoup import requests import time url = "https://www.umei.cc/weimeitupian/oumeitupian/nvsheng.htm" resp = requests.get(url) resp.encoding = 'utf-8' page = resp.text soup = BeautifulSoup(page,'html.parser') oAs = soup.find("div",class_='pic-list').find_all('a') aLinks = [] for a in oAs: aLinks.append("https://www.umei.cc"+str(a.get("href"))) print(aLinks) for link in aLinks: content = requests.get(link) content.encoding = 'utf-8' img = BeautifulSoup(content.text,'html.parser').find("div",class_='big-pic').find('img') src = img.get("src") print(img) print(src) img_name = src.split('/')[-1] img_resp = requests.get(src) with open('img/'+img_name,mode = "wb") as f: f.write(img_resp.content) time.sleep(1) f.close() resp.close() img_resp.close()
結果:
以上就是Python數(shù)據(jù)解析bs4庫使用BeautifulSoup方法示例的詳細內容,更多關于Python bs4 BeautifulSoup的資料請關注腳本之家其它相關文章!
相關文章
Python如何從txt文件中提取特定數(shù)據(jù)
這篇文章主要給大家介紹了關于Python如何從txt文件中提取特定數(shù)據(jù)的相關資料,有時我們會遇到需要按行讀取文本的情況,我們要讀取txt文件獲得數(shù)據(jù),需要的朋友可以參考下2023-08-08python Jieba分詞處理詳解【模式,詞庫的添加、刪除,自定義詞庫,失敗處理等】
這篇文章主要介紹了python Jieba分詞處理,結合實例形式詳細分析了python 使用jieba分詞的模式,詞庫的添加、刪除,自定義詞庫,失敗處理等相關操作技巧,需要的朋友可以參考下2023-07-07