jcyrss / baiyueheiyu

教程官网地址 www.byhy.net
4 stars 1 forks source link

store some files 为了 little班 practicing #1

Open jcyrss opened 4 years ago

jcyrss commented 4 years ago

c20191219a tcs-all.xlsx

jcyrss commented 4 years ago

for selenium , refer to

tcs-selenium.xlsx

jcyrss commented 4 years ago

sele-20191220b

参考

from selenium import webdriver

wd = webdriver.Chrome()
wd.implicitly_wait(5)

wd.get('http://127.0.0.1/mgr/sign.html')

# 根据 ID 选择元素,并且输入字符串
wd.find_element_by_id('username').send_keys('byhy')
wd.find_element_by_id('password').send_keys('88888888')

# 根据标签名查找元素
wd.find_element_by_tag_name('button').click()

# 先找到上层节点,缩小查找范围
sidebarMenu = wd.find_element_by_class_name('sidebar-menu')

# 再找到内部元素
elements = sidebarMenu.find_elements_by_tag_name('span')

menuTitles = []
for ele in elements:
    print(ele.text)
    menuTitles.append(ele.text)

print('**检查点**  侧边栏菜单是否正确', end='')
if menuTitles[:3] == ['客户', '药品', '订单'] :
    print('通过')
else:
    print('不通过!!')
    exit(1)

wd.quit()
jcyrss commented 4 years ago

参考答案

from selenium import webdriver
import time
# 导入Select类
from selenium.webdriver.support.ui import Select

#  添加 客户 或者 药品
#  由于 代码逻辑相同,封装在函数中
def addCustomerOrMedicion(field1,field2,field3):
    # 点击添加按钮
    wd.find_element_by_class_name('glyphicon-plus').click()

    # form-contorl 对应3个输入框
    inputs = wd.find_elements_by_css_selector('.add-one-area .form-control')

    # 输入 药品名称
    inputs[0].send_keys(field1)
    # 输入 编号
    inputs[1].send_keys(field2)
    # 输入 描述
    inputs[2].send_keys(field3)

    # 第1个 btn-xs 就是创建按钮, 点击创建按钮
    wd.find_element_by_css_selector('.add-one-area .btn-xs').click()

    # 等待界面刷新稳定
    time.sleep(1)

wd = webdriver.Chrome()
wd.implicitly_wait(5)

# 登录
wd.get('http://127.0.0.1/mgr/sign.html')

# 根据 ID 选择元素,并且输入字符串
wd.find_element_by_id('username').send_keys('byhy')
wd.find_element_by_id('password').send_keys('88888888')

# 点击登录
wd.find_element_by_tag_name('button').click()

# ****   添加 客户 和 药品 *****

# 点击药品菜单
wd.find_element_by_css_selector('.sidebar-menu li:nth-of-type(3)').click()
addCustomerOrMedicion('青霉素盒装1','YP-32342341','青霉素注射液,每支15ml,20支装')
addCustomerOrMedicion('青霉素盒装2','YP-32342342','青霉素注射液,每支15ml,30支装')
addCustomerOrMedicion('青霉素盒装3','YP-32342343','青霉素注射液,每支15ml,40支装')

# 点击客户菜单
wd.find_element_by_css_selector('.sidebar-menu li:nth-of-type(2)').click()
addCustomerOrMedicion('南京中医院1','2551867851','江苏省-南京市-秦淮区-汉中路-501')
addCustomerOrMedicion('南京中医院2','2551867852','江苏省-南京市-秦淮区-汉中路-502')
addCustomerOrMedicion('南京中医院3','2551867853','江苏省-南京市-秦淮区-汉中路-503')

# ****   添加 订单 *****

# 点击订单菜单
wd.find_element_by_css_selector('.sidebar-menu li:nth-of-type(4)').click()

# 点击添加按钮
wd.find_element_by_class_name('glyphicon-plus').click()

# 输入订单名称
name = wd.find_element_by_css_selector('.add-one-area .form-control')
name.send_keys('南中订单1')

# 两个select
selectElements = wd.find_elements_by_css_selector('.add-one-area select')

# 选择客户
Select(selectElements[0]).select_by_visible_text("南京中医院2")
# 选择药品
Select(selectElements[1]).select_by_visible_text("青霉素盒装1")

wd.find_element_by_css_selector(
    '.add-one-area input[type=number]')\
    .send_keys('100')

# 第1个 btn-xs 就是创建按钮, 点击创建按钮
wd.find_element_by_css_selector('.add-one-area .btn-xs').click()

wd.quit()
jcyrss commented 4 years ago

prac_py_0013_a1.zip


def analyzeFile2Excel():
    # 数据字段映射表
    fieldMap = {
        'dynamicTime' : '计划时间',
        'shipNameCn' : '中文船名',
        'shipNameEn' : '英文船名',
        'shipFlag' : '国籍(地区)',
        'shipLength' : '船长',
        'draft' : '吃水',
        'dynamicName' : '动态',
        'startBerth' : '起点泊位',
        'endBerth' : '终点泊位',
        'master' : '主引',
        'assistant' : '副引',
        'assistant2' : '其它引水',
        'orgShort' : '代理',
        'dTelephone' : '代理电话',
        '+++1' : '交通船',
        'channelName' : '航道',
        'headThruster:tailThruster' : '侧推',
        'remarks' : '备注',
    }

    # 创建一个Excel workbook 对象
    book = xlwt.Workbook()
    # 增加一个名为 '年龄表' 的sheet
    sh = book.add_sheet('引航')

    # 写标题栏
    for column, heading in enumerate(fieldMap.values()):
        sh.write(0, column, heading)

    with open('info1.txt','r',encoding='utf8') as f:
        row = 0
        while True:
            # 读入一行
            oneline =  f.readline()

            if not oneline:
                break

            # 一行对应1天的数据
            oneday = json.loads(oneline)

            # 再获取当天 的每行数据
            for line in oneday:
                row += 1
                # time.strftime('%Y%m%d %H:%M', time.localtime(int(line['dynamicTime'] / 1000)))
                # pprint(line)
                for column, field in enumerate(fieldMap.keys()):
                    # 没有的,暂时填空
                    if field not in line:
                        value = ''
                    else:
                        value = line[field]

                    # 计划时间要特殊处理
                    if field == 'dynamicTime' :
                        value = time.strftime('%Y%m%d %H:%M', time.localtime(int(line['dynamicTime'] / 1000)))
                        print(value)
                    # 侧推要特殊处理
                    if field == 'headThruster:tailThruster' :
                        if 'headThruster' not in line:
                            hvalue = '无'
                        else:
                            hvalue = line['headThruster']
                        if 'tailThruster' not in line:
                            tvalue = '无'
                        else:
                            tvalue = line['tailThruster']

                        value = f"首:{hvalue} 尾:{tvalue}"

                    sh.write(row, column, value)

    # 保存文件
    book.save('引航表.xls')

# getAllInfo2Text()
analyzeFile2Excel()

print('\n\n === 完成 ==== \n\n')
jcyrss commented 4 years ago

prac_py_0016_1.zip

jcyrss commented 4 years ago

prac_py_0019.zip

jcyrss commented 4 years ago

webapitool.zip

jcyrss commented 4 years ago

info1.zip

引航表.zip

jcyrss commented 4 years ago

hugo-demo.zip

jcyrss commented 4 years ago

getissue.zip

jcyrss commented 4 years ago

0016_1.txt

jcyrss commented 4 years ago

tcs-api.xlsx

jcyrss commented 4 years ago

hugo-demo.zip

jcyrss commented 4 years ago
videoFiles = '''
bandicam 2020-01-06 11-00-45-494.mp4
bandicam 2020-01-06 11-01-35-020.mp4
bandicam 2020-01-06 11-05-11-334.mp4
'''

ffmpegEXE = r'd:\tools\ffmpeg\bin\ffmpeg.exe'

import os

inputfiles = [line  for line in videoFiles.splitlines() if line.strip()]

def handle(inputfile):

    print(f'=====>{inputfile}')

    cmd = f'{ffmpegEXE} -i "{inputfile}" -af asetrate=44100*8.9/10,atempo=10/8.9 -c:v copy "mp_{inputfile}"'
    os.system(cmd)

for inputfile in inputfiles:
    handle(inputfile)

input('\n=== 转化完成 ===')  
jcyrss commented 4 years ago
targetDir = r'content'
pattern = r'<jcy-include>.*"(.+)"'

import os,sys,re,json
from pprint import pprint

# 加载 .jcyincludeLastMod.json
def load_jcyincludeLastMod():
   # 不存在,返回空字典
   if not os.path.exists('.jcyincludeLastMod.json'):
      return {}

   with open('.jcyincludeLastMod.json',encoding='utf8') as f:
      content = f.read()
      try:
         obj = json.loads(content)
         return obj
      except:
         print('!加载记录失败')
         return {}

# 更新 .jcyincludeLastMod.json
def update_jcyincludeLastMod(IncLastModRec):
     with open('.jcyincludeLastMod.json','w',encoding='utf8') as f:
         f.write(json.dumps(IncLastModRec,indent=3)) 

# 自定义修改规则函数
def my_replace(match):
   incFile = os.path.join(targetDir,match.group(1))
   with open(incFile,'r',encoding='utf8') as f:
      fileContent = f.read()

   return fileContent

# 从文件中 获取所有inc文件的最近修改时间记录
IncLastModRec = load_jcyincludeLastMod()

# dirpath 代表当前遍历到的目录名
# dirnames 是列表对象,存放当前dirpath中的所有子目录名
# filenames 是列表对象,存放当前dirpath中的所有文件名
for (dirpath, dirnames, filenames) in os.walk(targetDir):
   for fn in filenames:
      if not fn.endswith('.inc.md'):
         continue

      incFilePath = os.path.join(dirpath, fn)     
      # 对应的 ag.md 文件路径
      agFilePath = incFilePath.replace('.inc.md','.ag.md')
      agFileExists = os.path.exists(agFilePath)

      # 获取 inc.md 文件最后修改时间戳
      incFileMTime = os.path.getmtime(incFilePath)

      # 如果 记录中有该文件,而且 现有.ag.md文件
      if incFilePath in IncLastModRec  and  agFileExists :
         # 比较 inc.md 文件时间戳,和时间戳记录,
         # 如果相同,表示文件没有更新,就不需要进行后续处理了
         if IncLastModRec[incFilePath] == incFileMTime:
            # print(f'{incFilePath} :no update')
            continue

      with open(incFilePath, encoding='utf8') as f:
            content = f.read()

      if '<jcy-include>' not in content:
         continue

      newContent = re.sub(pattern, my_replace,content)

      # 否则替换
      print(f'{incFilePath} :更新')
      with open(agFilePath, "w", encoding='utf8') as f:
         f.write(newContent)

      # 更新时间戳
      IncLastModRec[incFilePath] = incFileMTime

# 更新整个记录的时间戳到文件
update_jcyincludeLastMod(IncLastModRec)
jcyrss commented 4 years ago

pilot.zip

jcyrss commented 4 years ago
import re

with open('stock.txt', 'r', encoding='utf-8') as f:
    stocklist = f.read()

while True:
    keywords = input('请输入要查询的股票名称或代码:')

    keywords = keywords.strip()

    # 如果输入为空
    if not keywords:
        continue

    # 如果是数字,
    if keywords.isdigit():
        # 一定要写全6位股票代码
        if len(keywords)<6:
            print('请写全6位股票代码')
            continue   

    pattern = f'^.*{keywords}.*$'

    # 否则进行搜索匹配,最多只显示10个
    retlist = re.findall(pattern,stocklist,re.M)[:10]
    for one in retlist:
        print(one)
jcyrss commented 4 years ago
targetDir = r'content'
pattern = r'<jcy-include>.*"(.+)"'

import os,sys,re,json
from pprint import pprint

# 加载 .jcyincludeLastMod.json
def load_jcyincludeLastMod():
   # 不存在,返回空字典
   if not os.path.exists('.jcyincludeLastMod.json'):
      return {}

   with open('.jcyincludeLastMod.json',encoding='utf8') as f:
      content = f.read()
      try:
         obj = json.loads(content)
         return obj
      except:
         print('!加载记录失败')
         return {}

# 更新 .jcyincludeLastMod.json
def update_jcyincludeLastMod(IncLastModRec):
     with open('.jcyincludeLastMod.json','w',encoding='utf8') as f:
         f.write(json.dumps(IncLastModRec,indent=3)) 

# 记录当前inc文件包含了哪些文件
thisIncFileIncludes = []

# 自定义修改规则函数
def my_replace(match):
   includedFile = os.path.join(targetDir,match.group(1))
   with open(includedFile,'r',encoding='utf8') as f:
      fileContent = f.read()

   thisIncFileIncludes.append((includedFile,os.path.getmtime(includedFile)))
   return fileContent

# 从文件中 获取所有inc文件的最近修改时间记录
IncLastModRec = load_jcyincludeLastMod()

# dirpath 代表当前遍历到的目录名
# dirnames 是列表对象,存放当前dirpath中的所有子目录名
# filenames 是列表对象,存放当前dirpath中的所有文件名
for (dirpath, dirnames, filenames) in os.walk(targetDir):
   for fn in filenames:
      if not fn.endswith('.inc.md'):
         continue

      incFilePath = os.path.join(dirpath, fn)     
      # 对应的 ag.md 文件路径
      agFilePath = incFilePath.replace('.inc.md','.ag.md')
      agFileExists = os.path.exists(agFilePath)

      # 获取 inc.md 文件最后修改时间戳
      incFileMTime = os.path.getmtime(incFilePath)

      # 如果 记录中有该文件,而且 现有.ag.md文件
      if incFilePath in IncLastModRec  and  agFileExists :
         # 比较 inc.md 文件时间戳,和时间戳记录,
         # 如果相同,表示inc文件没有更新
         if IncLastModRec[incFilePath]['inc_mtime'] == incFileMTime:
            # print(f'{incFilePath} :no update')

            # 如果它包含的文件也都没有更新,就不需要进行后续处理了
            includes = IncLastModRec[incFilePath]['includes']
            anyChange = False
            for ifile,mtime in includes:
               # print(ifile)
               if mtime != os.path.getmtime(ifile):
                  # print('changed')
                  anyChange = True
                  break

            if anyChange == False:
               continue

      with open(incFilePath, encoding='utf8') as f:
            content = f.read()

      # if '<jcy-include>' not in content:
      #    continue

      thisIncFileIncludes.clear()
      newContent = re.sub(pattern, my_replace,content)

      # 否则替换
      print(f'{incFilePath} :更新')
      with open(agFilePath, "w", encoding='utf8') as f:
         f.write(newContent)

      # 更新时间戳
      IncLastModRec[incFilePath] = {
         'inc_mtime': incFileMTime,
         # 为什么要先dumps再loads?就是要克隆新对象,
         # 否则最后所有的文件记录的都是同一个数据(最后一个)
         'includes' : json.loads(json.dumps(thisIncFileIncludes))
      }

# 更新整个记录的时间戳到文件
update_jcyincludeLastMod(IncLastModRec)
jcyrss commented 4 years ago
from random import randint
import time

class Tiger:
    classname = 'tiger'

    def __init__(self,weight=200):
        self.weight = weight

    def roar(self):
        print('wow!!!')
        self.weight -= 5

    def feed(self,food):
        if food == 'meat':
            self.weight += 10
            print('正确,体重 + 10')
        else :
            self.weight -= 10
            print('太惨了,体重 - 10')

class Sheep:
    classname = 'sheep'
    def __init__(self,weight=100):
        self.weight = weight

    def roar(self):
        print('mie~~')
        self.weight -= 5

    def feed(self,food):
        if food == 'grass':
            self.weight += 10
            print('正确,体重 + 10')
        else :
            self.weight -= 10
            print('太惨了,体重 - 10')

class Room:
    def __init__(self,num,animal):
        self.num = num
        self.animal = animal

rooms = []
for no in range(10):
    if randint(0,1):
        ani = Tiger(200)
    else:
        ani = Sheep(100)

    room = Room(no,ani)
    rooms.append(room)

startTime = time.time()
while True:
    curTime = time.time()
    if (curTime - startTime) > 120:
        print('\n\n **********  游戏结束 ********** \n\n')
        for idx, room in enumerate(rooms):
            print('房间 :%s' % (idx + 1), room.animal.classname, room.animal.weight)
        break

    roomno = randint(1, 10)
    room = rooms[roomno-1]  # why -1 ?
    ch = input('我们来到了房间# %s, 要敲门吗?[y/n]' % roomno)
    if ch == 'y':
        room.animal.roar()

    food = input('请给房间里面的动物喂食:')
    room.animal.feed(food.strip())
jcyrss commented 4 years ago
maxchar = input('请输入菱形的中心字母:')
# 将输入字母,转化为大写字母
maxchar = maxchar[0].upper()

# 得到输入字符对应的数字
intmaxchar = ord(maxchar)
# 得到第一个字母A对应的数字
intcharA  = ord('A')
halfLen = intmaxchar-intcharA

# 打印一行,
# 参数startPos指定从什么位置开始放A
# 参数halfLen就是打印最后一个字母的间隔
def printline(startPos,halfLen):

    outStr = ''
    # 先填入对应的空格数量
    outStr += ' '*startPos

    # 得到中轴线前面的字母序列
    tmp = []
    for ch in range(intcharA,intcharA+halfLen-startPos):
        tmp.append(chr(ch))

    outStr += ''.join(tmp)

    # 计算中轴线上的字母是什么
    curMaxChar = chr(intmaxchar-startPos)
    outStr += curMaxChar

    # 得到中轴线后面的字母序列: 反向
    tmp.reverse()
    outStr += ''.join(tmp)

    print(outStr)

# 先打印菱形的上半段,像这样
#    A
#   ABA
#  ABCBA
# ABCDCBA
for startpos in range(halfLen,-1,-1):
    printline(startpos,halfLen)

# 再打印菱形的下半段,像这样
#  ABCBA
#   ABA
#    A
for startpos in range(1,halfLen+1):
    printline(startpos,halfLen)
jcyrss commented 3 years ago
from selenium import webdriver
import re
from time import time

wd = webdriver.Chrome()
wd.implicitly_wait(10)
wd.get('https://y.qq.com/n/yqq/toplist/27.html#stat=y_new.toplist.menu.27')

# 获取整个歌曲列表
songList = wd.find_element_by_class_name(
    'songlist__list').find_elements_by_class_name('songlist__item')

for song in songList:
    rank = song.find_element_by_class_name(
        'songlist__rank').get_attribute('outerHTML')

    if 'icon_rank_up' not in rank:  # 非上升歌曲
        continue

    songName = song.find_element_by_class_name(
        'js_song').get_attribute('outerHTML')

    p = re.compile(r'>(.+?)<')
    songName = p.findall(songName)[0]
    # print(songName)

    singerName = song.find_element_by_class_name(
        'singer_name').text

    print(f'{songName:<15}: {singerName}')
jcyrss commented 7 months ago

image