python requests,BeautifulSoup批量下載360圖片

本代碼演示通過python的requests,BeautifulSoup庫批量下載360圖片,並保存在本機的路徑

代碼如下:

#BeautifulSoup庫是網頁爬蟲解析庫,主要用來對HTML源代碼進行解析,方便顯示並讀取相應的標籤數據
#1、首先導入相應的庫
import requests
from bs4 import BeautifulSoup
import random
import os
import time
#2、對網站進行get請求
def gethtml(kward):
try:
url="https://image.so.com" #設置360網站的搜索頁面的前面部分網址
kw={"q":kward} #設置關鍵字變量kw
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36"} # 設置網頁請求頭
response = requests.get(url, params=kw,headers=headers) ##偽裝瀏覽器對url進行get請求,傳遞的參數是kw
response.encoding=response.apparent_encoding #根據網頁內容解析出編碼格式並賦值給response.encoding
html=response.text #將網頁源代碼賦值給html
soup=BeautifulSoup(html,'html.parser') #使用html.parser對html代碼進行解析,並賦值給soup變量
print(soup.head) #打印網頁源代碼的頭部信息
images=soup.find_all('img') #查找源代碼裡所有的圖片標籤
path="F://明星照片//"+kward+"//" #設置圖片的存儲本機的路徑
for img in images: #遍歷所有的img標籤信息
print(img.attrs["src"]) #打印遍歷出來的圖片表情的src屬性值
url1=img.attrs["src"] #設置url1為遍歷出來的圖片表情的src屬性值
response1=requests.get(url=url1,headers=headers)

#上行代碼偽裝瀏覽器對url1,即圖片網站進行get請求並將請求結果賦值給response1
response1.encoding=response1.apparent_encoding #根據網頁內容解析出編碼格式並賦值給response1.encoding
html1=response1.content #將圖片網址的二進制源代碼賦值給html1
abspath=path+str(random.random())+".jpg" #設置存儲路勁為abspath
with open(abspath,"wb") as f: #打開文件的絕對路徑,並對文件進行寫入操作,並設置為f
f.write(html1) #將源代碼寫入f文件
f.close() #關閉f文件
print(img.attrs["src"]+"下載成功") #打印下載成功的提示
time.sleep(0.2) #設置時間休眠0.2秒
except: #如果接受錯誤時
print("爬取失敗") #打印爬取失敗

代碼運行結果如下圖所示:

python requests,BeautifulSoup批量下載360圖片


分享到:


相關文章: