Python數據解析bs4庫使用BeautifulSoup方法示例
更新時間:2023年08月21日 09:59:25 作者:YiYa_咿呀
這篇文章主要為大家介紹了Python數據解析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數據解析bs4庫使用BeautifulSoup方法示例的詳細內容,更多關于Python bs4 BeautifulSoup的資料請關注腳本之家其它相關文章!
相關文章
python GUI庫圖形界面開發(fā)之PyQt5下拉列表框控件QComboBox詳細使用方法與實例
這篇文章主要介紹了python GUI庫圖形界面開發(fā)之PyQt5下拉列表框控件QComboBox詳細使用方法與實例,需要的朋友可以參考下2020-02-02
Python基于火山引擎豆包大模型搭建QQ機器人詳細教程(2024年最新)
這篇文章主要介紹了Python基于火山引擎豆包大模型搭建QQ機器人詳細的相關資料,包括開通模型、配置APIKEY鑒權和SDK安裝等步驟,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2025-01-01
Python函數命名空間和作用域(Local與Global)
這篇文章主要介紹了Python函數命名空間和作用域分別介紹Local與Global模式,內容詳細,具有一定的參考價值,需要的小伙伴可以參考一下2022-03-03

