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實踐之使用Pandas進行數(shù)據(jù)分析
在數(shù)據(jù)分析領(lǐng)域,Python的Pandas庫是一個非常強大的工具。這篇文章將為大家詳細介紹如何使用Pandas進行數(shù)據(jù)分析,希望對大家有所幫助2023-04-04
Python super( )函數(shù)用法總結(jié)
今天給大家?guī)淼闹R是關(guān)于Python的相關(guān)知識,文章圍繞著super( )函數(shù)展開,文中有非常詳細的介紹及代碼示例,需要的朋友可以參考下2021-06-06
Pandas數(shù)據(jù)結(jié)構(gòu)中Series屬性詳解
本文主要介紹了Pandas數(shù)據(jù)結(jié)構(gòu)中Series屬性詳解,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-04-04
在Python的一段程序中如何使用多次事件循環(huán)詳解
循環(huán)是我們在日常開發(fā)中是必不可少會遇到的,下面這篇文章主要給大家介紹了關(guān)于在Python的一段程序中如何使用多次事件循環(huán)的相關(guān)資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考借鑒,下面來一起看看吧。2017-09-09

