会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132578个问题
Python 全系列/第一阶段:Python入门/序列 27919楼
Python 全系列/第五阶段:数据库编程/MySQL数据库的使用 27920楼

'''
使用工厂模式、单例模式实现如下需求:
(1) 电脑工厂类 ComputerFactory 用于生产电脑 Computer。工厂类使用单例模式,也就是说只能有一个工厂对象。
(2) 工厂类中可以生产各种品牌的电脑:联想、华硕、神舟
(3) 各种品牌的电脑使用继承实现:
(4) 父类是 Computer 类,定义了 calculate 方法
(5) 各品牌电脑类需要重写父类的 calculate
'''

class ComputerFactory:

    __obj = None
    __init_flag = True

    def create_computer(self,brand):
        if brand == "联想":
            return Lenovo()
        elif brand == "华硕":
            return Asus()
        elif brand == "神舟":
            return Hasee()
        else:
            return "未知品牌,无法创建"

    def __new__(cls, *args, **kwargs):
        if cls.__obj == None:  #当前的类对象cls下的类属性是否为空
            cls.__obj = object.__new__(cls)
        return cls.__obj

    def __init__(self):
        if ComputerFactory.__init_flag:  #等于if MySingleton.__init_flag == True
            print("init ComputerFactory...")
            ComputerFactory.__init_flag = False  #保证了只调用1次初始化


class Computer:
    def calculate(self):
        print("生产电脑啦!")

class Lenovo(Computer):  #联想
    def calculate(self):
        print("生产联想电脑啦!")

class Asus(Computer):  #华硕
    def calculate(self):
        print("生产华硕电脑啦!")

class Hasee(Computer):  #神舟
    def calculate(self):
        print("生产神舟电脑啦!")


factory = ComputerFactory()
c1 = factory.create_computer("联想")
print(c1.calculate())

factory2 = ComputerFactory()
c2 = factory2.create_computer("华硕")
print(c2.calculate())

image.png

老师,请问一下:

1、运行图(如上显示)里的None是哪里来的

2、单例模式这个还是有点不太理解为什么要这么写(如下显示)

image.png


Python 全系列/第一阶段:Python入门/面向对象 27921楼
Python 全系列/第一阶段:Python入门/编程基本概念 27922楼
JAVA 全系列/第八阶段:SpringBoot与MybatisPlus/Lombok 27924楼
JAVA 全系列/(旧的隐藏)第二十一阶段:百战商城项目(Spring Cloud最新架构)/百战商城项目 27925楼
Python 全系列/第七阶段:网页编程基础/html5 27926楼
JAVA 全系列/第三阶段:数据库编程/Oracle 数据库的使用 27927楼

from dbutie import Mydb
class MyService():

    def __init__(self):
        self.user = None
    def login(self,uname,password):
        sql = "select * from t_user where uname=%s and password=%s"
        user = Mydb().query_one(sql,uname,password)
        if user:
            self.user = user
            return True
        else:
            return False

    def add_music(self,files):
        for f in files:
            start = f.rfind("/")+1
            end = f.rfind(".mp3")
            music_name = f[start:end]
            #根据歌名查询数据库是否存在同样歌曲
            sql = "select * from t_music where music_name=%s"
            music = Mydb().query_one(sql,music_name)
            if music:
                #查询关联表t_list 该用户是否添加了这首歌
                sql = "select * from t_list where uid=%s and uid=%s"
                t_list = Mydb().query_one(sql,music[0],self.user[0])
                if not t_list:
                    sql = "insert into t_list(mid,uid) values(%s,%s)"
                    Mydb().exeMDL(sql,music[0],self.user[0])
            else:
                #将音乐保存到t_music里面
                sql = "insert into t_music(music_name,path) values(%s,%s)"
                mid = Mydb().exeDML(sql,music_name,f)

                #用户选择的音乐保存到t_list
                sql = "insert into t_list(mid,uid) values(%s,%s)"
                Mydb().exeDML(sql,mid,self.user[0])
                
                
                
import pymysql
class Mydb():
    config = {
        "host":"127.0.0.1",
        "user":"root",
        "password":"199759guo",
        "db":"music_project",
        "charset":"utf8"
    }
    def __init__(self):
        self.connection = pymysql.connect(**Mydb.config)
        self.cursor = self.connection.cursor()
    #插入,修改,删除数据
    def close(self):
        if self.cursor:
            self.cursor.close()
        if self.connection:
            self.connection.close()
    def exeDML(self,sql,*args):
        try:
            #执行sql
            count = self.cursor.execute(sql,args)
            id = self.connection.insert_id()
            #提交事务
            self.connection.commit()
            return id
        except Exception as e:
            print(e)
            if self.connection:
                self.connection.rollback()
        finally:
            self.close()
    def query_one(self,sql,*args):
        try:
            #执行sql
            self.cursor.execute(sql,args)
            #获取结果集
            return self.cursor.fetchone()
        except Exception as e:
            print(e)
        finally:
            self.close()
    def query_all(self,sql,*args):
        try:
            #执行sql
            self.cursor.execute(sql,args)
            #获取结果集
            return self.cursor.fetchall()
        except Exception as e:
            print(e)
        finally:
            self.close()

                

from MyService import MyService
import tkinter
from tkinter.filedialog import askopenfilenames
class PlayWindow:
    def __init__(self,myService):
        self.myService = myService

    def impMusoc(self,event):
        print("导入了音乐按钮")
        #打开磁盘选择音乐
        files = askopenfilenames(filetype=(["mp3","*.mp3"],))
        #导入音乐,将选择的音乐保存到数据库
        self.myService.add_music(files)

    def playMusic(self,even):
        print("点击了音乐按钮")
    def deleteMusic(self,even):
        print("删除了音乐")
    def showWindow(self):
        #显示窗口
        top = tkinter.Tk()

        #添加按钮
        play_button = tkinter.Button(top,text="播放")
        imp_button = tkinter.Button(top,text="导入音乐")
        delete_button = tkinter.Button(top,text="删除")
        play_button.grid(row=0,column=0,padx=5,pady=5)
        imp_button.grid(row=0,column=2,padx=5,pady=5)
        delete_button.grid(row=0,column=4,padx=5,pady=5)
        # 添加列表
        listbox = tkinter.Listbox(top)
        listbox.grid(row=1,column=0,padx=5,pady=5,columnspan=9)
        #给按钮添加事件
        imp_button.bind("<ButtonRelease-1>",self.impMusoc)
        play_button.bind("<ButtonRelease-1>",self.playMusic)
        delete_button.bind("<ButtonRelease-1>",self.deleteMusic)
        top.mainloop()

if __name__ == "__main__":
    uname = input("请输入用户名:")
    password = input("请输入密码:")
    myservice = MyService()
    if myservice.login(uname,password):
        print("登录成功")
        playwindow = PlayWindow(myservice)
        playwindow.showWindow()
    else:
        print("登录失败")

老师,您好,报这个是什么意思啊。image.png

Python 全系列/第五阶段:数据库编程/项目-音乐播放器-旧 27928楼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>07cookie案例</title>
    <style>
        .loginDiv{border: 1px solid #666;padding: 30px;width: 300px;}
        .welcomeDiv{border: 1px solid #666;padding: 30px;width: 300px;margin-top: 30px;display: none;}
        .welcome1 span{color: green;font-size: 20px;font-weight: bold;}
    </style>
</head>
<body>
    <div class="loginDiv">
        <div class="login1">
            <label for="">姓名:</label>
            <input type="text" name="" id="userName">
        </div>
        <div class="login1">
            <label for="">密码:</label>
            <input type="text" name="" id="passWord">
        </div>
        <button id="login">登录</button>
        <button id="regist">注册</button>
    </div>
    <div class="welcomeDiv">
        <div class="welcome1">欢迎回来, <span id="nickNameSpan">未登录</span></div>
        <button id="reset">注销登录</button>
    </div>
    <script>
        (function(){
            var login = document.querySelector('#login');
            var regist = document.querySelector('#regist');
            var reset = document.querySelector('#reset');
            var loginDiv = document.querySelector('.loginDiv');
            var welcomeDiv = document.querySelector('.welcomeDiv');
            var userName = document.querySelector('#userName');
            var passWord = document.querySelector('#passWord');
            var nickNameSpan = document.querySelector('#nickNameSpan');
            //表示一个自动登录的功能
            function getCookie(){                
                var cookie = document.cookie;
                var cookieArr = cookie.split(';');
                var finalObj = {};
                for(var i = 0; i < cookieArr.length; i++){
                    var tempArr = cookieArr[i].trim().split('=');
                    finalObj[tempArr[0]] = tempArr[1];
                }
                return  finalObj;
            }
            var cookieObj = getCookie();
            if(cookieObj.nickName != undefined){
                if(cookieObj.nickName.length != 0){
                    welcomeDiv.style.display = 'block';
                    loginDiv.style.display = 'none';
                    nickNameSpan.innerHTML = cookieObj.nickName;
                }
            }

            login.onclick = function(){
                var xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function(){
                    if(xhr.readyState == 4){
                        if(xhr.status == 200){
                            var data = JSON.parse(xhr.responseText);
                            if(data.loginStatusCode == 1){
                                welcomeDiv.style.display = 'block';
                                loginDiv.style.display = 'none';
                                nickNameSpan.innerHTML = data.nickName;
                            }
                        }
                    }
                };
                var formData = new FormData();
                formData.append('uname', userName.value);
                formData.append('pword', passWord.value);
                xhr.open('post', '07cookie案例.php', true);
                xhr.send(formData)
            }
            
            //注销
            reset.onclick = function(){
                userName.value = '';
                passWord.value = '';
                welcomeDiv.style.display = 'none';
                loginDiv.style.display = 'block';
                var expires = new Date(new Date().getTime() + 1).toGMTString();
                document.cookie = "nickName=beixi; expires" + expires;
            }
        })()
    </script>
</body>
</html>

老师,我这个注销的时候cookie清除不了是什么原因

WEB前端全系列/第九阶段:HTML5新特性模块/(旧)H5新特性 27929楼

代码:

import requests
from fake_useragent import UserAgent
from lxml import etree
from time import sleep
url="https://www.lagou.com/zhaopin/2/?filterOption=3&sid=021dfdfa56f24b11810b1f18e04902eb"
headers={"User-Agent":UserAgent().chrome}
sleep(2)
resp=requests.get(url,headers=headers)
resp.encoding="utf-8"
html=resp.text
print(html)
e=etree.HTML(html)
a=e.xpath('//div[@class="p_top"]//h3/text()')
for i in a:
    print(i)

运行结果:


        body {

            margin: 0;

            width: 100%;

            height: 100%;

        }


        @keyframes loadingAnimation {

            0% {

                transform: translate3d(0, 0, 0);

            }


            50% {

                transform: translate3d(0, -10px, 0);

            }

        }


        .loading-info {

            text-align: center;

            height: 100%;

            position: relative;

            background: #fff;

            top: 50%;

            margin-top: -37px;

        }


        .loading-info .animation-word {

            width: 100%;

        }


        .loading-info .animation-word p {

            margin-top: 10px;

            color: #9fa3b0;

        }


        .animation-word .component-l,

        .animation-word .component-a,

        .animation-word .component-g,

        .animation-word .component-o,

        .animation-word .component-u {

            display: inline-block;

            width: 40px;

            height: 42px;

            line-height: 42px;

            font-family: Helvetica Neue, Helvetica, Arial, Hiragino Sans GB, Hiragino Sans GB W3, Microsoft YaHei UI, Microsoft YaHei, WenQuanYi Micro Hei, sans-serif;

            font-weight: bolder;

            font-size: 40px;

            color: #eceef2;

            vertical-align: top;

            -webkit-animation-fill-mode: both;

            animation-fill-mode: both;

            -webkit-animation: loadingAnimation 0.6s infinite linear alternate;

            -moz-animation: loadingAnimation 0.6s infinite linear alternate;

            animation: loadingAnimation 0.6s infinite linear alternate;

        }


        .animation-word .component-a {

            -webkit-animation-delay: 0.1s;

            -moz-animation-delay: 0.1s;

            animation-delay: 0.1s;

        }


        .animation-word .component-g {

            -webkit-animation-delay: 0.2s;

            -moz-animation-delay: 0.2s;

            animation-delay: 0.2s;

        }


        .animation-word .component-o {

            -webkit-animation-delay: 0.3s;

            -moz-animation-delay: 0.3s;

            animation-delay: 0.3s;

        }


        .animation-word .component-u {

            -webkit-animation-delay: 0.4s;

            -moz-animation-delay: 0.4s;

            animation-delay: 0.4s;

        }

    </style>

</head>


<body>

    <div class="loading-info">

        <div class="info-inner">

            <div class="animation-word">

                <span class="component-l">L</span>

                <span class="component-a">a</span>

                <span class="component-g">g</span>

                <span class="component-o">o</span>

                <span class="component-u">u</span>

                <p class="gray">正在加载中...</p>

            </div>

        </div>

    </div>

    <script>

        var securityPageName = "securityCheck";

        !function () {

            function e(c) {

                var l, m, n, o, p, q, r, e = function () {

                    var a = location.hostname;

                    return "localhost" === a || /^(\d+\.){3}\d+$/.test(a) ? a : "." + a.split(".").slice(-2).join(".")

                }(),

                    f = function (a, b) {

                        var f = document.createElement("script");

                        f.setAttribute("type", "text/javascript"), f.setAttribute("charset", "UTF-8"), f.onload = f.onreadystatechange = function () {

                            d && "loaded" != this.readyState && "complete" != this.readyState || b()

                        }, f.setAttribute("src", a), "IFRAME" != c.tagName ? c.appendChild(f) : c.contentDocument ? c.contentDocument.body ? c.contentDocument.body.appendChild(f) : c.contentDocument.documentElement.appendChild(f) : c.document && (c.document.body ? c.document.body.appendChild(f) : c.document.documentElement.appendChild(f))

                    },

                    g = function (a) {

                        var b = new RegExp("(^|&)" + a + "=([^&]*)(&|$)"),

                            c = window.location.search.substr(1).match(b);

                        return null != c ? unescape(c[2]) : null

                    },

                    h = {

                        get: function (a) {

                            var b, c = new RegExp("(^| )" + a + "=([^;]*)(;|$)");

                            return (b = document.cookie.match(c)) ? unescape(b[2]) : null

                        },

                        set: function (a, b, c, d, e) {

                            var g, f = a + "=" + encodeURIComponent(b);

                            c && (g = new Date(c).toGMTString(), f += ";expires=" + g), f = d ? f + ";domain=" + d : f, f = e ? f + ";path=" + e : f, document.cookie = f

                        }

                    },

                    i = function (a) {

                        if (a) {

                            window.location.replace(a)

                        }

                    },

                    j = function (a, c) {

                        c || a.indexOf("security-check.html") > -1 ? i(c) : i(a);

                    };

                window.location.href, l = g("seed") || "", m = g("ts"), n = g("name"),

                    o = g("callbackUrl"),

                    p = g("srcReferer") || "", "null" !== n && l && n && o, l && m && n && (f("dist/" + n + ".js", function () {

                        var n, a = (new Date).getTime() + 1728e5,

                            d = "",

                            f = {},

                            g = window.gt || c.contentWindow.gt;

                        try {

                            d = (new g()).a();

                        } catch (k) { console.log(k) }

                        if (d) {

                            (h.set("__lg_stoken__", d, a, e, "/"), j(p, o))

                        }

                    }))

            }

            function j(a) {

                if (!f && !g && document.addEventListener) return document.addEventListener("DOMContentLoaded", a, !1);

                if (!(h.push(a) > 1))

                    if (f) ! function () {

                        try {

                            document.documentElement.doScroll("left"), i()

                        } catch (a) {

                            setTimeout(arguments.callee, 0)

                        }

                    }();

                    else if (g) var b = setInterval(function () {

                        /^(loaded|complete)$/.test(document.readyState) && (clearInterval(b), i())

                    }, 0)

            }

            var d, f, g, h, i, a = 0,

                b = (new Date).getTime(),

                c = window.navigator.userAgent;

            c.indexOf("MSIE ") > -1 && (d = !0),

                f = !(!window.attachEvent || window.opera),

                g = /webkit\/(\d+)/i.test(navigator.userAgent) && RegExp.$1 < 525,

                h = [],

                i = function () {

                    for (var a = 0; a < h.length; a++) h[a]()

                };

            j(function () {

                var b, a = window.navigator.userAgent.toLowerCase();

                return "micromessenger" !== a.match(/micromessenger/i) || "wkwebview" == a.match(/wkwebview/i) ?

                    (e(document.getElementsByTagName("head").item(0)), void 0)

                    :

                    (b = document.createElement("iframe"), b.style.height = 0, b.style.width = 0, b.style.margin = 0, b.style.padding = 0, b.style.border = "0 none", b.name = "tokenframe", b.src = "about:blank", b.attachEvent ? b.attachEvent("onload", function () {

                        e(b)

                    }) : b.onload = function () {

                        e(b)

                    }, (document.body || document.documentElement).appendChild(b), void 0)

            })

        }();


    </script>

<script type="text/javascript" crossorigin="anonymous" src="https://www.lagou.com/upload/oss.js?v=1010"></script></body>


</html>

老师请问一下,为什么我使用requests.get方法爬取拉勾网的时候,返回回来的HTML代码和使用f12查看的源代码不一致?对于这个问题当我使用selenium库爬取的时候就不会出现,请问老师在爬取拉勾网的时候是不是必须使用selenium库进行爬取呢?如果我想用requests.get方法来爬取拉勾网,有没有什么办法可以解决返回的HTML和源码不一致的问题?

Python 全系列/第十五阶段:Python 爬虫开发/爬虫反反爬- 27930楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637