利用Python为女神制作一个专属网站
作者:周萝卜 时间:2021-07-26 23:16:30
先来看一下效果吧,只要有足够的照片素材,捕获女神的心就指日可待
怎么样,看起来还可以吧
下面就一起来完成吧
数据准备
首先是测试图片的获取,毕竟萝卜哥当前还没有那么多女神的照片
这里我使用如下网站的高清图片,嗯,各个都是大美女
抓取的代码比较简单
import requests
import json
def get_pic():
headers = {"Accept": "application/json, text/javascript, */*; q=0.01",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_0_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36",
"Cookie": "Hm_lvt_6e8dac14399b608f633394093523542e=1607173561; Hm_lvt_ea4269d8a00e95fdb9ee61e3041a8f98=1621344383; Hm_lpvt_ea4269d8a00e95fdb9ee61e3041a8f98=1621344423",
"Referer": "http://lab.mkblog.cn/wallpaper/"}
pic_url = "http://lab.mkblog.cn/wallpaper/api.php?cid=6&start=0&count=100"
pic_res = requests.get(pic_url, headers=headers)
pic_res_json = pic_res.json()
pic_info = pic_res_json.get("data")
pic_url = []
num = 0
try:
for i in pic_info:
if num % 5 == 0:
pic_url.append(i["url"])
if num % 5 == 1:
pic_url.append(i["img_1600_900"])
if num % 5 == 2:
pic_url.append(i["img_1366_768"])
if num % 5 == 3:
pic_url.append(i["img_1280_800"])
if num % 5 == 4:
pic_url.append(i["img_1024_768"])
num += 1
except:
pass
return pic_url
def save_pic_url(data):
json.dump(data, open("pic_url.json", 'w'))
if __name__ == '__main__':
pic_url = get_pic()
save_pic_url(pic_url)
因为网站提供了不同分辨率的图片,所以也就根据一定的规则来获取不同分辨率的图片了。
接下来是获取渣男话术,哈哈哈哈,又是一个有趣的网站,感兴趣的朋友自行查看吧
由于这个接口是有调用频率限制的,那么也抓取一些到本地吧
def get_data():
headers = {"Accept": "application/xml",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_0_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36"}
url = "https://nihaowua.90so.net/api/wus"
res = requests.get(url, headers=headers).json()
return res
if __name__ == '__main__':
data_list = []
for i in range(10):
data = get_data()
data_list.append(data.get("title"))
time.sleep(10)
json.dump(data_list, open("data.json", "w"))
网站搭建
首先我们还是通过简单的 Flask 来进行后台的搭建
index 视图
@app.route('/', methods=['GET', 'POST'])
def index():
pic_list = json.load(open("pic_url.json"))
seg = int(len(pic_list)/4)
data = []
socre = 5
for n in pic_list[:seg]:
tmp_data = []
pic_url = random.choice(pic_list)
tmp_data.append(pic_url)
tmp_data.append(pic_list.index(n))
data.append(tmp_data)
return render_template('index.html', data=data, score=socre)
还是比较简单的,拿到图片地址文件中的数据后,根据规则展示一部分图片
下面是 index.html 的部分核心代码
图片展示代码
{% for p in data %}
<article class="white-panel">
<img class="thumb" data-original="{{ p[0] }}">
<h1><a href="{{ url_for('nvshen', id=p[1]) }}" rel="external nofollow" title="去投票" target="_blank">爱你😘</a>
</h1>
</article>
{% endfor %}
懒加载图片的 js 代码
function getData(page) {
var xhr = new XMLHttpRequest();
xhr.responseType = "json";
xhr.open('POST', '/api/getdata/' + page, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onload = function (ev) {
if(this.status === 200) {
if(this.response['end'] === true) {
flag = false;
}
var mydata = this.response['msg'];
//console.log(mydata[1][2]);
for(var i=0, len=mydata.length; i<len; i++){
var myurl = mydata[i][0];
var htmlText = '<article class="white-panel">' +
'<img data-original=' + myurl +' class="thumb">' +
'<h1>' +
'<a href=URL title="去投票" target="_blank">'.replace("URL", Flask.url_for("nvshen", {id: "1"})) +
"爱你😘" + '</a>' +
'</h1>' +
'<p>' +
'<div id="starBg" class="stars-bg">' +
'{% if score == 1 %}' +
'<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="star-active" style="width: 20%"></a>' +
'{% elif score == 2 %}' +
'<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="star-active" style="width: 40%"></a>' +
'{% elif score == 3 %}' +
'<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="star-active" style="width: 60%"></a>' +
'{% elif score == 4 %}' +
'<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="star-active" style="width: 80%"></a>' +
'{% elif score == 5 %}' +
'<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="star-active" style="width: 100%"></a>' +
'{% else %}' +
'<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="star-active" style="width: 0%"></a>' +
'{% endif %}' +
'</div>' +
'</p>' +
'</article>';
var script = '<script>' +
'$(function(){' +
'$("img.thumb").lazyload();' +
'})' +
'<\/script>';
$('#gallery-wrapper').append(htmlText);
$('body').append(script);
}
}else if(this.status === 422) {
console.log("get data error");
}
};
xhr.send();
}
这里用到了 接口 getdata,我们来看看其实现
@app.route('/api/getdata/<int:page>', methods=['POST'])
def get_data(page):
pic_list = json.load(open("pic_url.json"))
seg = 0
seg_page = int(len(pic_list)/4)
end = False
if page == 2:
seg = seg_page
seg_page = seg*2
elif page == 3:
seg = seg_page*2
seg_page = seg + seg_page
elif page == 4:
seg = seg_page*3
seg_page = int(len(pic_list)) + 1
end = True
elif page == 1:
pass
else:
return jsonify({"msg": "error page id", "code": 422}), 422
data = []
socre = 1
for n in pic_list[seg:seg_page]:
tmp_data = []
pic_url = random.choice(pic_list)
tmp_data.append(pic_url)
data.append(tmp_data)
return jsonify({"msg": data, "code": 200, "end": end}), 200
这里有一个分页的机制,用于懒加载图片
接下来就是详情页,也就是展示“渣男语录”的页面
@app.route('/nvshen/<id>/', methods=['GET', 'POST'])
def nvshen(id):
pic_list = json.load(open("pic_url.json"))
pic_url = pic_list[int(id)]
data = json.load(open("data.json"))
return render_template('nvshen.html', nvshenid=id, main_url=pic_url, data_list=data, user_score=5)
分别拿到当前图片的地址和抓取好的渣男语录,返回给前端
对于 nvshen.html 代码也比较简单,直接来个循环即可
<section id="gallery-wrapper">
{% for d in data_list %}
<article class="white-panel">
<!--<img data-original="{{ d }}" class="thumb">-->
<h1><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{{ d }}</a>
</h1>
</article>
{% endfor %}
</section>
这样,我们一个简单的女神网站就完成了
服务部署
Python web 的部署,我一般使用 gunicorn
gunicorn 基本配置
# coding=utf-8
import sys
import os
import multiprocessing
path_of_current_file = os.path.abspath(__file__)
path_of_current_dir = os.path.split(path_of_current_file)[0]
_file_name = os.path.basename(__file__)
sys.path.insert(0, path_of_current_dir)
worker_class = 'sync'
workers = multiprocessing.cpu_count() * 2 + 1
chdir = path_of_current_dir
worker_connections = 1000
timeout = 30
max_requests = 2000
graceful_timeout = 30
loglevel = 'info'
reload = True
debug = False
access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" "%({X-Real-IP}i)s"'
bind = "%s:%s" % ("127.0.0.1", 5001)
pidfile = '%s/logs/%s.pid' % (path_of_current_dir, _file_name)
errorlog = '%s/logs/%s_error.log' % (path_of_current_dir, _file_name)
accesslog = '%s/logs/%s_access.log' % (path_of_current_dir, _file_name)
然后再用如下命令就可以启动了
/root/miniconda3/bin/gunicorn -D -c /home/nvshen/app/gunicorn app:app
来源:https://mp.weixin.qq.com/s/HUzP2SXHfzkeYeAQd5ZJsg
标签:Python,网站
0
投稿
猜你喜欢
可以拖动的div 实现代码第1/2页
2024-03-19 17:46:20
python实现字符串连接的三种方法及其效率、适用场景详解
2023-07-27 19:57:32
SQL列名无效 sql查询列名 sql返回列名
2009-09-03 13:19:00
php下关于Cannot use a scalar value as an array的解决办法
2023-10-29 22:29:23
关于php unset对json_encode的影响详解
2023-07-06 08:33:52
tensorflow之并行读入数据详解
2021-09-20 14:42:30
使用python绘制常用的图表
2022-02-16 19:47:33
MySQL存储过程的查询命令介绍
2024-01-13 22:34:49
MySQL备份与恢复之热备(3)
2024-01-21 04:50:04
站长必须要了解的九条平面设计常识
2008-06-07 14:33:00
python 提取tuple类型值中json格式的key值方法
2022-10-04 20:05:32
简单了解python列表和元组的区别
2022-02-11 17:14:43
js实现无需数据库的县级以上联动行政区域下拉控件
2024-01-17 01:05:53
Python3对称加密算法AES、DES3实例详解
2022-08-16 19:52:56
通过PHP current函数获取未知字符键名数组第一个元素的值
2023-11-15 04:52:07
jquery中文手册上的一点错误--说说p标签失去焦点
2009-09-13 21:24:00
PyQt5 QLineEdit输入的子网字符串校验QRegExp实现
2022-05-08 16:47:58
Python中使用PyQt把网页转换成PDF操作代码实例
2021-12-04 11:31:19
浅析JSON序列化与反序列化
2024-03-22 12:50:05
设计模式-自动完成
2010-11-30 21:44:00