草庐IT

利用Python为女神制作一个专属网站

liuliumei 2023-03-28 原文

 一、数据准备

首先是测试图片的获取,毕竟小明当前还没有那么多女神的照片

这里我使用如下网站的高清图片,嗯,各个都是大美女

 

 

 

抓取的代码比较简单

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"'

Python学习交流群:780296133
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

 

好了,这样就可以把网站地址告诉女神了,坐等被夸!

 
 
 

有关利用Python为女神制作一个专属网站的更多相关文章

  1. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  2. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  3. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  4. ruby-on-rails - 渲染另一个 Controller 的 View - 2

    我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>

  5. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  6. ruby - 为什么 SecureRandom.uuid 创建一个唯一的字符串? - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?

  7. ruby-on-rails - Rails - 从另一个模型中创建一个模型的实例 - 2

    我有一个正在构建的应用程序,我需要一个模型来创建另一个模型的实例。我希望每辆车都有4个轮胎。汽车模型classCar轮胎模型classTire但是,在make_tires内部有一个错误,如果我为Tire尝试它,则没有用于创建或新建的activerecord方法。当我检查轮胎时,它没有这些方法。我该如何补救?错误是这样的:未定义的方法'create'forActiveRecord::AttributeMethods::Serialization::Tire::Module我测试了两个环境:测试和开发,它们都因相同的错误而失败。 最佳答案

  8. ruby - Ping ruby 网站? - 2

    在Ruby中可以使用哪些替代方法来ping一个ip地址?标准库“ping”库的功能似乎非常有限。我对在这里滚动我自己的代码不感兴趣。有没有好的gem?我应该接受它并忍受它吗?(我在Linux上使用Ruby1.8.6编写代码) 最佳答案 net-ping值得一看。它允许TCPping(如标准ruby​​ping),但也允许UDP、HTTP和ICMPping。ICMPping需要root权限,但其他则不需要。 关于ruby-Pingruby网站?,我们在StackOverflow上找到一个类

  9. ruby - 用 Ruby 编写一个简单的网络服务器 - 2

    我想在Ruby中创建一个用于开发目的的极其简单的Web服务器(不,不想使用现成的解决方案)。代码如下:#!/usr/bin/rubyrequire'socket'server=TCPServer.new('127.0.0.1',8080)whileconnection=server.acceptheaders=[]length=0whileline=connection.getsheaders想法是从命令行运行这个脚本,提供另一个脚本,它将在其标准输入上获取请求,并在其标准输出上返回完整的响应。到目前为止一切顺利,但事实证明这真的很脆弱,因为它在第二个请求上中断并出现错误:/usr/b

  10. ruby - 一个 YAML 对象可以引用另一个吗? - 2

    我想让一个yaml对象引用另一个,如下所示:intro:"Hello,dearuser."registration:$introThanksforregistering!new_message:$introYouhaveanewmessage!上面的语法只是它如何工作的一个例子(这也是它在thiscpanmodule中的工作方式。)我正在使用标准的ruby​​yaml解析器。这可能吗? 最佳答案 一些yaml对象确实引用了其他对象:irb>require'yaml'#=>trueirb>str="hello"#=>"hello"ir

随机推荐