一、準備作業
用python來實作對百度圖片的爬取并保存,以情緒圖片為例,百度搜索可得到下圖所示
f12打開原始碼

在此處可以看到這次我們要爬取的圖片的基本資訊是在img - scr中
二、代碼實作
這次的爬取主要用了如下的第三方庫
import re
import time
import requests
from bs4 import BeautifulSoup
import os
簡單構思可以分為三個小部分
1.獲取網頁內容
2.決議網頁
3.保存圖片至相應位置
下面來看第一部分:獲取網頁內容
baseurl = 'https://cn.bing.com/images/search?q=%E6%83%85%E7%BB%AA%E5%9B%BE%E7%89%87&qpvt=%e6%83%85%e7%bb%aa%e5%9b%be%e7%89%87&form=IGRE&first=1&cw=418&ch=652&tsc=ImageBasicHover'
head = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36 Edg/92.0.902.67"}
response = requests.get(baseurl, headers=head) # 獲取網頁資訊
html = response.text # 將網頁資訊轉化為text形式
是不是so easy
第二部分決議網頁才是大頭
來看代碼
Img = re.compile(r'img.*src="(.*?)"') # 正則運算式匹配圖片
soup = BeautifulSoup(html, "html.parser") # BeautifulSoup決議html
#i = 0 # 計數器初始值
data = [] # 存盤圖片超鏈接的串列
for item in soup.find_all('img', src=""): # soup.find_all對網頁中的img—src進行迭代
item = str(item) # 轉換為str型別
Picture = re.findall(Img, item) # 結合re正則運算式和BeautifulSoup, 僅回傳超鏈接
for b in Picture:
data.append(b)
#i = i + 1
return data[-1]
# print(i)
這里就運用到了BeautifulSoup以及re正則運算式的相關知識,需要有一定的基礎哦
下面就是第三部分:保存圖片
for m in getdata(
baseurl='https://cn.bing.com/images/search?q=%E6%83%85%E7%BB%AA%E5%9B%BE%E7%89%87&qpvt=%e6%83%85%e7%bb%aa%e5%9b%be%e7%89%87&form=IGRE&first=1&cw=418&ch=652&tsc=ImageBasicHover'):
resp = requests.get(m) #獲取網頁資訊
byte = resp.content # 轉化為content二進制
print(os.getcwd()) # os庫中輸出當前的路徑
i = i + 1 # 遞增
# img_path = os.path.join(m)
with open("path{}.jpg".format(i), "wb") as f: # 檔案寫入
f.write(byte)
time.sleep(0.5) # 每隔0.5秒下載一張圖片放入D://情緒圖片測驗
print("第{}張圖片爬取成功!".format(i))
各行代碼的解釋已經給大家寫在注釋中啦,不明白的地方可以直接私信或評論哦~
下面是完整的代碼
import re
import time
import requests
from bs4 import BeautifulSoup
import os
# m = 'https://tse2-mm.cn.bing.net/th/id/OIP-C.uihwmxDdgfK4FlCIXx-3jgHaPc?w=115&h=183&c=7&r=0&o=5&pid=1.7'
'''
resp = requests.get(m)
byte = resp.content
print(os.getcwd())
img_path = os.path.join(m)
'''
def main():
baseurl = 'https://cn.bing.com/images/search?q=%E6%83%85%E7%BB%AA%E5%9B%BE%E7%89%87&qpvt=%e6%83%85%e7%bb%aa%e5%9b%be%e7%89%87&form=IGRE&first=1&cw=418&ch=652&tsc=ImageBasicHover'
datalist = getdata(baseurl)
def getdata(baseurl):
Img = re.compile(r'img.*src="(.*?)"') # 正則運算式匹配圖片
datalist = []
head = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36 Edg/92.0.902.67"}
response = requests.get(baseurl, headers=head) # 獲取網頁資訊
html = response.text # 將網頁資訊轉化為text形式
soup = BeautifulSoup(html, "html.parser") # BeautifulSoup決議html
# i = 0 # 計數器初始值
data = [] # 存盤圖片超鏈接的串列
for item in soup.find_all('img', src=""): # soup.find_all對網頁中的img—src進行迭代
item = str(item) # 轉換為str型別
Picture = re.findall(Img, item) # 結合re正則運算式和BeautifulSoup, 僅回傳超鏈接
for b in Picture: # 遍歷串列,取最后一次結果
data.append(b)
# i = i + 1
datalist.append(data[-1])
return datalist # 回傳一個包含超鏈接的新串列
# print(i)
'''
with open("img_path.jpg","wb") as f:
f.write(byte)
'''
if __name__ == '__main__':
os.chdir("D://情緒圖片測驗")
main()
i = 0 # 圖片名遞增
for m in getdata(
baseurl='https://cn.bing.com/images/search?q=%E6%83%85%E7%BB%AA%E5%9B%BE%E7%89%87&qpvt=%e6%83%85%e7%bb%aa%e5%9b%be%e7%89%87&form=IGRE&first=1&cw=418&ch=652&tsc=ImageBasicHover'):
resp = requests.get(m) #獲取網頁資訊
byte = resp.content # 轉化為content二進制
print(os.getcwd()) # os庫中輸出當前的路徑
i = i + 1 # 遞增
# img_path = os.path.join(m)
with open("path{}.jpg".format(i), "wb") as f: # 檔案寫入
f.write(byte)
time.sleep(0.5) # 每隔0.5秒下載一張圖片放入D://情緒圖片測驗
print("第{}張圖片爬取成功!".format(i))
最后的運行截圖

三、總結
這次僅僅是保存了29張圖片,在爬取其他網頁的時候,用的方法都是大同小異,最主要還是根據網頁的內容靈活變換,觀察它的原始碼,另外有部分網站可能會有反爬措施,爬的時候要注意哦~如果還有不懂的地方,歡迎留言私信
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/400568.html
標籤:python
上一篇:【藍橋杯真題】2021年藍橋杯省賽A組題目決議+代碼(python組)
下一篇:資料分析基礎——資料規整
