How to use Python to make an NBA crawler with interface

Liu Zaoqi 2020-11-16 16:19:39
use python make nba crawler


One 、 Preface

Sometimes it turns code into a program with an interface , Will be extremely convenient to use , Although there are a lot of ready-made GUI System , however Apply someone else's code , It's hard to avoid embarrassment , So this article will use Python Combination of reptiles wxpython Modules construct a NBA Crawler Software , The demonstration effect is as follows

The framework of this paper will be divided into two parts :

  1. structure GUI Interface
  2. For example, apply the crawler framework

It mainly involves Python Module has

  • requests
  • wx
  • pymysql
  • pandas

Two 、GUI Interface design

First of all, introduce the process :GUI Interface design explanation

\Longrightarrow

Insert interface background image

Design GUI The code idea of the interface is actually very simple , First, import. wx library

# One 、 Refer to the module
import wx

The module referenced here is wxpython modular , establish GUI There are many modules of , Common are PyQtTkinter etc. . Each of these modules has its own advantages and disadvantages , Readers can refer to the relevant materials to choose from .

# Two 、 Define global variables ( Create panels and layouts )
class MyFrame(wx.Frame):
def __init__(self, parent, id):
wx.Frame.__init__(self, parent, id, 'titlename',size=(400, 300))
panel = wx.Panel(self)
self.bt_confirm = wx.Button(panel, label='name1')
self.bt_confirm.Bind(wx.EVT_BUTTON,self.OnclickSubmit)
self.bt_cancel = wx.Button(panel, label='name2')
self.bt_cancel.Bind(wx.EVT_BUTTON,self.OnclickCancel)
self.InitUI()

Define global variables for Elementary GUI To build a formal window + Button layout , You don't need to build a module . But for advanced GUI In terms of investment systems, such as , Global variables are particularly important , In other words, global variables need to be placed in a py Initialization in file .

The above code is the code to create the part , Personalized layout needs to be set by adding containers , It will be presented later in the total code .

# 3、 ... and 、 Call local variables and bind Events
def InitUI(self):
""" Click on InitUI, Execution method """
def OnclickSubmit(self,event):
""" binding OnclickSubmit event """

Simply put, it's binding events , This event is the effect of clicking the corresponding button . This is the whole GUI At the heart of , If you're doing a check-in system , Then you have to bind an imported employee list txt File Events .

# Four 、GUI Execute the script
if __name__ == '__main__':
app = wx.App() # initialization
frame = MyFrame(parent=None,id=-1)
frame.Show()
app.MainLoop() # Call the main loop
del app

This is the basic routine of step four .

3、 ... and 、 Example implementation

With a simple NBA The crawler system, for example , First create panels and layouts ?

class MyFrame(wx.Frame):
def __init__(self, parent, id):
wx.Frame.__init__(self, parent, id, 'NBA visualization ',size=(400, 300))
panel = wx.Panel(self)
self.bt_confirm = wx.Button(panel, label=' Contract information ')
self.bt_confirm.Bind(wx.EVT_BUTTON,self.OnclickSubmit)
self.bt_cancel = wx.Button(panel, label=' Empty ')
self.bt_cancel.Bind(wx.EVT_BUTTON,self.OnclickCancel)
self.bt_imf = wx.Button(panel, label=' visualization ')
self.bt_imf.Bind(wx.EVT_BUTTON,self.Onclickvisual)
self.bt_team = wx.Button(panel, label=' Team information ',pos=(280,20))
self.bt_team.Bind(wx.EVT_BUTTON,self.Onclickteam)
self.bt_obtain = wx.Button(panel, label=' Player information ',pos=(20,20))
self.bt_obtain.Bind(wx.EVT_BUTTON,self.Onclickimfor)
self.bt_ml = wx.Button(panel, label=' Scoreboard ')
self.bt_ml.Bind(wx.EVT_BUTTON,self.Onclickmql)
self.title = wx.StaticText(panel, label="NBA visualization ")
self.label_user = wx.StaticText(panel, label=" Team name ")
self.text_user = wx.TextCtrl(panel, style=wx.TE_LEFT)
self.label_pwd = wx.StaticText(panel, label=" Player name ")
self.text_pwd = wx.TextCtrl(panel, style=wx.TE_LEFT)
self.label_path = wx.StaticText(panel, label=" Storage path ")
self.text_pathword = wx.TextCtrl(panel, style=wx.TE_LEFT)

Then add the container , To arrange horizontally

 hsizer_user = wx.BoxSizer(wx.HORIZONTAL)
hsizer_user.Add(self.label_user, proportion=0, flag=wx.ALL, border=5)
hsizer_user.Add(self.text_user, proportion=1, flag=wx.ALL, border=5)
hsizer_pwd = wx.BoxSizer(wx.HORIZONTAL)
hsizer_pwd.Add(self.label_pwd, proportion=0, flag=wx.ALL, border=5)
hsizer_pwd.Add(self.text_pwd, proportion=1, flag=wx.ALL, border=5)
hsizer_path = wx.BoxSizer(wx.HORIZONTAL)
hsizer_path.Add(self.label_path, proportion=0, flag=wx.ALL, border=5)
hsizer_path.Add(self.text_pathword, proportion=1, flag=wx.ALL, border=5)
hsizer_button = wx.BoxSizer(wx.HORIZONTAL)
hsizer_button.Add(self.bt_confirm, proportion=0, flag=wx.ALIGN_CENTER, border=5)
hsizer_button.Add(self.bt_cancel, proportion=0, flag=wx.ALIGN_CENTER, border=5)
hsizer_button.Add(self.bt_imf, proportion=0, flag=wx.ALIGN_CENTER, border=5)
hsizer_button.Add(self.bt_ml, proportion=0, flag=wx.ALIGN_CENTER, border=5)

Then add the container , Arrange vertically

 vsizer_all = wx.BoxSizer(wx.VERTICAL)
vsizer_all.Add(self.title, proportion=0, flag=wx.BOTTOM | wx.TOP | wx.ALIGN_CENTER,
border=15)
vsizer_all.Add(hsizer_user, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=45)
vsizer_all.Add(hsizer_pwd, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=45)
vsizer_all.Add(hsizer_path, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=45)
vsizer_all.Add(hsizer_button, proportion=0, flag=wx.ALIGN_CENTER | wx.TOP, border=15)
panel.SetSizer(vsizer_all)
self.InitUI()

The next step is event binding

 def InitUI(self):
""" Click the instructions button , Execution method """
def OnQuit1(self,e):
""" Input notes """
def OnclickSubmit(self,event):
""" Click on the contract information button , Execution method """
def Onclickvisual(self,event):
""" Click the visualization button , Execution method """
def OnclickCancel(self,event):
""" Click the clear button , Execution method """
def Onclickimfor(self,event):
""" Click the player name button , Execution method """
def Onclickteam(self,event):
""" Click the team name button , Execution method """
def Onclickmql(self,event):
""" Click on the scoreboard button , Execution method """

The event handling here is not very difficult , Readers can try to innovate on their own , Finally, execute the script

if __name__ == '__main__':
app = wx.App() # initialization
frame = MyFrame(parent=None,id=-1) # example MyFrame class , And pass the parameters
frame.Show() # Display window
app.MainLoop() # Call the main loop method

The effect is as shown in the picture ?

Add : Insert background image

Want to build a personalized system , The most important thing you want is that you can't change the background . Here I choose to use a picture of old ke .

I believe that some readers will feel an independent stand-alone GUI Software will be more suitable for itself , I'm just like that , therefore , In setting the background image after GUI Packaging required , So you need to specify the binary image base64 turn , After the conversion, it will be stored in py The document is followed by import Packaging for media . The binary code conversion is as follows :

import base64
with open("name.jpg","rb") as f:
base64_str = base64.b64encode(f.read())
with open('%s.py' % picture_name.replace('.', '_'), 'w+') as f1:
f1.write(base64_str)
f1.close()

At this point, you can get base64 Coded py file , And then reference it in the code . Because packaging can't pack pictures , So here's a slightly more complicated implementation “ Referring to the specified picture base64 code —— Create a picture —— Insert background image ” function !

Finally, with a little modification, the background color of the text is changed to transparent . The framework for writing this code is very fixed , So we learned from the great gods , The basic code framework is as follows :

# Here we need to insert two sentences into the main event
panel.Bind(wx.EVT_ERASE_BACKGROUND,self.OnEraseBack)
self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBack)
# Reference code and create images
from bg_png import img as bg
def pic(picPath,picName):
tmp = open(picPath, 'wb')
tmp.write(base64.b64decode(picName))
tmp.close()
pic('bg.png',bg)
# Insert a picture ( Sub event Indented )
def OnEraseBack(self,event):
''' Add picture background '''
try :
dc = event.GetDC()
if not dc:
dc = wx.ClientDC(self)
rect = self.GetUpdateRegion().GetBox()
dc.SetClippingRect(rect)
dc.Clear()
bmp = wx.Bitmap(nowpath+r'\bg.png')
dc.DrawBitmap(bmp, -500, -100)
except :
pass
# Change text background color to transparent
# First step : In the main event wx.StaticText Replacing the TransparentStaticText
# The second step : repeat StaticText Control
class TransparentStaticText(wx.StaticText):
def __init__(self, parent, id=wx.ID_ANY, label='', pos=wx.DefaultPosition, size=wx.DefaultSize,
style=wx.TRANSPARENT_WINDOW, name='TransparentStaticText'):
wx.StaticText.__init__(self, parent, id, label, pos, size, style, name)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_ERASE_BACKGROUND, lambda event: None)
self.Bind(wx.EVT_SIZE, self.OnSize)
def OnPaint(self, event):
bdc = wx.PaintDC(self)
dc = wx.GCDC(bdc)
font_face = self.GetFont()
font_color = self.GetForegroundColour()
dc.SetFont(font_face)
dc.SetTextForeground(font_color)
dc.DrawText(self.GetLabel(), 0, 0)
def OnSize(self, event):
self.Refresh()
event.Skip()

The final effect is as shown in the figure :

Notice if you want to pack , The following three modules need to be introduced into the code :

import six
import packaging
import packaging.version
import packaging.specifiers
import packaging.requirements

-END-

This article is from WeChat official account. - Get up early Python(zaoqi-python) , author : Contributors

The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the yunjia_community@tencent.com Delete .

Original publication time : 2020-11-08

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[Liu Zaoqi]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database