python基于爬蟲+django,打造個性化API接口
簡述
今天也是同事在做微信小程序的開發(fā),需要音樂接口的測試,可是用網(wǎng)易云的開放接口比較麻煩,也不能進行測試,這里也是和我說了一下,所以就用爬蟲寫了個簡單網(wǎng)易云歌曲URL的爬蟲,把數(shù)據(jù)存入mysql數(shù)據(jù)庫,再利用django封裝裝了一個簡單的API接口,給同事測試使用。
原理
創(chuàng)建django項目,做好基礎(chǔ)的配置,在views里寫兩個方法,一個是從mysql數(shù)據(jù)庫中查數(shù)據(jù)然后封裝成API,一個是爬蟲方法,數(shù)據(jù)扒下來以后,通過django的ORM把數(shù)據(jù)插入到mysql數(shù)據(jù)庫中。
這里的路由也是對應(yīng)兩個,一個是爬蟲的請求路由(就是運行路由),一個是接口路由,MODEL層里也是為了方便,就設(shè)了兩個字段,一個是歌曲名稱,一個是URL地址。
代碼如下
views文件代碼
from django.shortcuts import render,HttpResponse import requests from lxml import etree from .models import Api # Create your views here. def api_wy(request): api = Api.objects.all() return render(request, "index.html",locals()) def pc(request): url = 'https://music.163.com/discover/toplist?id=3779629' headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3861.400 QQBrowser/10.7.4313.400' } data = requests.get(url=url, headers=headers) html = etree.HTML(data.text) music_list = html.xpath('//ul[@class="f-hide"]/li/a') music_lis = [] # 存放歌曲信息 for music in music_list: music_name = music.xpath('./text()')[0] # 獲取歌曲名稱 music_id_all = music.xpath('./@href')[0] # 獲取a標簽內(nèi)容 music_id = music_id_all.split('=')[-1] # 將a標簽內(nèi)容進行數(shù)據(jù)清洗,提取歌曲的id download_music = music_name + ' ' + f'http://music.163.com/song/media/outer/url?id={music_id}.mp3' # 將歌曲名稱和url進行拼接 music_lis.append(download_music) print(download_music) for url in music_lis: try: url_name = url.split(' ')[0] # 獲取名稱 url_music = url.split(' ')[1] # 獲取url Api.objects.create(name=url_name,url=url_music) print("正在插入數(shù)據(jù)") except: print("charushibai") return HttpResponse("正在下載")
URL路由文件
from django.contrib import admin from django.urls import path from api.views import api_wy,pc urlpatterns = [ path('admin/', admin.site.urls), path('api/',api_wy), path("pc/",pc), ]
Models層面
from django.db import models # Create your models here. class Api(models.Model): name = models.CharField('歌曲名稱', max_length=100) url = models.CharField("歌曲地址",max_length=300) class Meta: verbose_name = '歌曲API' verbose_name_plural = verbose_name def __str__(self): return self.name
其他的也就沒什么可說的了,也是一個比較簡單的測試需求,就是為了省點事情才弄得
好了,今天就到這了,拜拜
以上就是python基于爬蟲+django,打造個性化API接口的詳細內(nèi)容,更多關(guān)于python api接口的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python調(diào)用Matplotlib繪制分布點并且添加標簽
這篇文章主要為大家詳細介紹了python調(diào)用Matplotlib繪制分布點并且添加標簽的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-05-05Python3.x檢查內(nèi)存可用大小的兩種實現(xiàn)
本文將介紹如何使用Python 3實現(xiàn)檢查Linux服務(wù)器內(nèi)存可用大小的方法,包括使用Python標準庫實現(xiàn)和使用Linux命令實現(xiàn)兩種方式,感興趣可以了解一下2023-05-05python模塊與C和C++動態(tài)庫相互調(diào)用實現(xiàn)過程示例
這篇文章主要為大家介紹了python模塊與C和C++動態(tài)庫之間相互調(diào)用的實現(xiàn)過程示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-11-11python自動化測試之DDT數(shù)據(jù)驅(qū)動的實現(xiàn)代碼
這篇文章主要介紹了python自動化測試之DDT數(shù)據(jù)驅(qū)動的實現(xiàn)代碼,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-07-07