Python爬取網(wǎng)站圖片并保存的實現(xiàn)示例
更新時間:2021年02月26日 09:54:14 作者:筷子夾豆腐.
這篇文章主要介紹了Python爬取網(wǎng)站圖片并保存的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
先看看結(jié)果吧,去bilibili上拿到的圖片=-=

第一步,導入模塊
import requests from bs4 import BeautifulSoup
requests用來請求html頁面,BeautifulSoup用來解析html
第二步,獲取目標html頁面
hd = {'user-agent': 'chrome/10'} # 偽裝自己是個(chrome)瀏覽器=-=
def download_all_html():
try:
url = 'https://www.bilibili.com/' # 將要爬取網(wǎng)站的地址
request = requests.get(url, timeout=30, headers=hd) # 獲取改網(wǎng)站的信息
request.raise_for_status() # 判斷狀態(tài)碼是否為200,!=200顯然爬取失敗
request.encoding = request.apparent_encoding # 設(shè)置編碼格式
return request.text # 返回html頁面
except:
return ''
第三步,分析網(wǎng)站html構(gòu)造
1、顯示網(wǎng)站html代碼

2、找到圖片位置

3、分析


第四步,直接上代碼注釋夠詳細=-=
def parse_single_html(html):
soup = BeautifulSoup(html, 'html.parser') # 解析html,可以單獨去了解一下他的使用
divs = soup.find_all('div', class_='card-pic') # 獲取滿足條件的div,find_all(所有)
for div in divs: # 瞞住條件的div有多個,我們單獨獲取
p = div.find('p') # 有源代碼可知,每個div下都有一個p標簽,存儲圖片的title,獲取p標簽
if p == None:
continue
title = p['title'] # 獲取p標簽中的title屬性,用來做圖片的名稱
img = div.find('img')['src'] # 獲取圖片的地址
if img[0:6] != 'https:': # 根據(jù)源代碼發(fā)現(xiàn),有的地址缺少"https:"前綴
img = 'https:' + img # 如果缺少,我們給他添上就行啦,都據(jù)情況而定
response = requests.get(img) # get方法得到圖片地址(有的是post、put)基本是get
with open('./Img/{}.png'.format(title), 'wb') as f: # 創(chuàng)建用來保存圖片的.png文件
f.write(response.content) # 注意,'wb'中的b 必不可少!!
parse_single_html(download_all_html()) # 最后調(diào)用我們寫的兩個函數(shù)就行啦,

查看結(jié)果

到此這篇關(guān)于Python爬取網(wǎng)站圖片并保存的實現(xiàn)示例的文章就介紹到這了,更多相關(guān)Python爬取圖片保存內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python使用openpyxl打開及讀取excel表格過程
openpyxl是一個Python庫,用于讀寫Excel?2010?xlsx/xlsm文件,它允許你輕松工作與Excel表格,進行數(shù)據(jù)處理和分析,支持讀取、創(chuàng)建和修改Excel文件,甚至可以在Excel中插入圖表等,安裝非常簡單,只需要使用pip命令即可2024-09-09

