新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
python如何保存網(wǎng)頁圖片格式
要使用Python保存網(wǎng)頁圖片,可以使用requests庫(kù)來獲取網(wǎng)頁內(nèi)容,然后使用BeautifulSoup庫(kù)來解析HTML并提取圖片鏈接,使用requests庫(kù)下載圖片并將其保存到本地,以下是詳細(xì)步驟:

1、安裝所需庫(kù):
pip install requests pip install beautifulsoup4
2、導(dǎo)入所需庫(kù):
import os import requests from bs4 import BeautifulSoup
3、獲取網(wǎng)頁內(nèi)容:
url = 'https://example.com' # 替換為你想要保存圖片的網(wǎng)頁URL response = requests.get(url) html_content = response.text
4、解析HTML并提取圖片鏈接:
soup = BeautifulSoup(html_content, 'html.parser')
img_tags = soup.find_all('img')
img_urls = [img['src'] for img in img_tags]
5、下載并保存圖片:
save_dir = 'images' # 設(shè)置保存圖片的文件夾
if not os.path.exists(save_dir):
os.makedirs(save_dir)
for img_url in img_urls:
img_data = requests.get(img_url).content
img_name = os.path.basename(img_url)
with open(os.path.join(save_dir, img_name), 'wb') as f:
f.write(img_data)
將以上代碼整合到一個(gè)Python腳本中,即可實(shí)現(xiàn)使用Python保存網(wǎng)頁圖片的功能。
網(wǎng)頁標(biāo)題:python如何保存網(wǎng)頁圖片格式
轉(zhuǎn)載注明:http://www.dlmjj.cn/article/coicjgs.html


咨詢
建站咨詢
