新聞中心
在進(jìn)行文章撰寫(xiě)時(shí),尋找適當(dāng)?shù)呐鋱D是一項(xiàng)重要的任務(wù)。然而,盡管我嘗試在各大網(wǎng)站上尋找合適的圖片資源,但往往面臨兩個(gè)主要問(wèn)題:其一,這些網(wǎng)站大多需要付費(fèi)使用,這無(wú)疑增加了我的經(jīng)濟(jì)負(fù)擔(dān);其二,即使有些網(wǎng)站提供免費(fèi)圖片,但其質(zhì)量卻令人堪憂(yōu)。

為了解決這個(gè)令人頭疼的問(wèn)題,我自己動(dòng)手一個(gè)搜索圖片的網(wǎng)站,解決了日常文章配圖的問(wèn)題。整體的界面如下:
圖片的加載采用瀑布流的模式。
這個(gè)網(wǎng)站是站在巨人的肩膀上完成的,為什么這么說(shuō)呢?圖片的來(lái)源是調(diào)用頭條號(hào)的圖片庫(kù),前端是使用github開(kāi)源的瀑布流插件。
分析頭條圖片庫(kù)的API
打開(kāi)頭條號(hào)發(fā)布文章,點(diǎn)擊添加圖片,會(huì)出現(xiàn)如下圖
通過(guò)分析這個(gè)接口,發(fā)現(xiàn)它并沒(méi)有做認(rèn)證,攜帶幾個(gè)路徑參數(shù)。
在無(wú)痕瀏覽器重放這個(gè)接口,這能正常獲取數(shù)據(jù),如下圖:
現(xiàn)在圖片的數(shù)據(jù)源找到了,可以把它做成接口,給前端用戶(hù)調(diào)用了。這里我選擇熟悉的FastAPI做接口。
接口代碼實(shí)現(xiàn)
從上述分析接口發(fā)現(xiàn),路徑參數(shù)只有三個(gè)參數(shù)是動(dòng)態(tài)變化的。所以,我們把它做成變量的形式:
from pydantic import BaseModel
class TuotiaoParams(BaseModel):
page: int=0#圖片頁(yè)數(shù)
size: int = 30#展示圖片的數(shù)量
term: str=None#搜索的關(guān)鍵字然后,把請(qǐng)求頭條號(hào)API接口封裝成一個(gè)函數(shù),方便后續(xù)調(diào)用:
import requests
from fake_useragent import UserAgent
from schemas import TuotiaoParams
from loguru import logger
def search_pic(params:TuotiaoParams):
try:
url = "https://dficimage.toutiao.com/api/proxy/get"
params = {
"from": params.page,
"size": params.size,
"term": params.term,
"search_id": 7274062948258316581,
"user_id": 68783357974,
"media_id": 1609422238702596,
"search_from": "search",
"position": "article_icstock",
"platform": "toutiaohao",
"path": "/micro/search"
}
res = requests.get(
url,
params=params,
headers={"User-Agent":UserAgent().random},
timeout=10
)
if res.json().get("code") == 1:
logger.info("獲取頭條的圖片的數(shù)據(jù):{}".format(res.json()))
return res.json().get("data").get("data").get("hits")
except Exception as e:
logger.error('抓取頭條的圖片錯(cuò)誤:{}'.format(e))利用FastAPI把頭條號(hào)API做成接口模式:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from toutiao import search_pic
from schemas import SearchKeyWork,TuotiaoParams
import uvicorn
app = FastAPI()
# 添加跨域中間件
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # 允許所有來(lái)源訪問(wèn)
allow_methods=["*"], # 允許所有HTTP方法
allow_headers=["*"], # 允許所有HTTP頭
)
@app.post("/image_toutaio")
def iamge_toutiao(params:TuotiaoParams):
return {"code":1,"data":search_pic(params)}
if __name__ == "__main__":
uvicorn.run(app)執(zhí)行如下代碼啟動(dòng)程序,就可以正常訪問(wèn)接口:
python main.py這樣后臺(tái)的接口,就完成了。
前端搭建
前端采用的github上開(kāi)源的瀑布流圖片展示模板,然后,自己添加搜索功能的。
https://github.com/heikaimu/vue3-waterfall-plugin
下載vue3-waterfall-plugin項(xiàng)目到本地,執(zhí)行如下代碼安裝依賴(lài):
pnpm install安裝完依賴(lài),執(zhí)行如下代碼,啟動(dòng)前端:
pnpm run dev啟動(dòng)成功之后,輸入想要的圖片進(jìn)行搜索,如圖:
- 項(xiàng)目的地址: https://github.com/didiplus/vue3-waterfall-plugin
- 演示地址: http://img.kwpmp.cn/
- 演示備用地址: https://cerulean-florentine-527213.netlify.app/
本文題目:利用開(kāi)放接口,如何一步步打造自己的獨(dú)特圖片網(wǎng)站
轉(zhuǎn)載來(lái)于:http://m.fisionsoft.com.cn/article/djgdeep.html


咨詢(xún)
建站咨詢(xún)
