Python 자동화 데이터 드라이브(자신의 일상 연습 노트를 옮겨 싣기)

56183 단어
하나.execl 데이터 구동
1.xlutils 간략한 설명
가이드 패키지: pip3 install xlutils
주의⚠️:xlutils는 Execl 파일을 표시할 때 식별만 합니다.xls 접미사 파일입니다.xlsx 접미사 파일이 해석되었습니다.xlsx 접미사 파일이 파괴됩니다
2. 인터페이스 자동화에서execl에 대한 간단한 읽기
#!/user/bin/env python
#coding:utf-8
#Author:shenqiang

'''xlrd    ,       '''
import xlrd
import os

'''       '''
def base_path(filename = None):
    return os.path.join(os.path.dirname(__file__),filename)

'''      '''
work = xlrd.open_workbook(base_path('tryExeclRead.xls'))

'''     sheet       '''
sheet = work.sheet_by_index(0)
# sheet = work.sheet_by_name()

'''        '''
print(sheet.nrows)

'''       , 10 , 3 '''
print(sheet.cell_value(9,2))

3. execl 파일의 내용 바꾸기
#!/user/bin/env python
#coding:utf-8
#Author:shenqiang

import xlrd
import os
from xlutils.copy import copy

'''       '''
def base_path(filename = None):
    return os.path.join(os.path.dirname(__file__),filename)

'''    '''
work = xlrd.open_workbook(base_path('tryExeclRead.xls'))
'''            '''
file_content = copy(work)
'''         sheet '''
file = file_content.get_sheet(0)
# print(file_content)
'''          '''
file.write(9,3,'  ')
'''    '''
file_content.save(base_path('tryExeclRead.xls'))

4.configparser 구성 파일의 읽기(서비스 및 데이터베이스 연결)
프로필 이름
config.ini
파일 내용:
[linux]
ip:10.0.13.26
port:22
username:root
password:W2ynE6b58wheeFho

[mysql]
ip:10.0.13.26
port:22
username:root
password:W2ynE6b58wheeFho

파일 이름
tryConfigparser.py
파일 내용:
#!/user/bin/env python
#coding:utf-8
#Author:shenqiang

import os
import configparser

'''       '''
def base_path(filename = None):
    return os.path.join(os.path.dirname(__file__),filename)

def getConfigparser(Linux = 'linux'):
    '''     '''
    config = configparser.ConfigParser()
    '''      '''
    config.read(base_path('config.ini'))
    
    ip = config.get(Linux,'ip')
    port = config.get(Linux,'port')
    username = config.get(Linux,'username')
    password = config.get(Linux,'password')
    return [ip,port,username,password]

  '''      '''
for i in range(len(getConfigparser())):
    print(getConfigparser()[i])

5.mysql에서 자주 사용하는 조작 명령
  MySQL  
sudo / usr / local / mysql / support - files / mysql.server start

  MySQL  
sudo / usr / local / mysql / support - files / mysql.server stop

  MySQL  
sudo / usr / local / mysql / support - files / mysql.server restart

  MySQL   
mysql - u root - p
Password:     (shen6409175)
  
'''     '''
show databases;
'''     '''
use students;
'''   '''
show tables;
'''   '''
create table student(
-> id int primary key,
-> name varchar(50),
-> age varchar(10),
-> address varchar(100)
-> );
'''     '''
desc student;
'''     '''
show create table student \g;

둘.MySQL 데이터 구동
1. 데이터베이스 조회
#!/user/bin/env python
#coding:utf-8
#Author:shenqiang
import pymysql

def connectMysql():
    try:
        '''     '''
        connect = pymysql.connect(
            host='127.0.0.1',
            user='root',
            password='shen6409175',
            db='students'
        )
    except Exception as  e:
        return e.args
    else:
        '''    '''
        cur = connect.cursor()
        '''SQL    '''
        # sql = 'select * from student where id = %s'
        # params = (1,)
        # '''  '''
        # cur.execute(sql,params)
        # '''       '''
        # data = cur.fetchone()
        # return datas
        sql = 'select * from student'
        '''  '''
        cur.execute(sql)
        '''      '''
        datas = cur.fetchall()
        ''''''
        # for data in datas:
        #     print(data)
        ''''''
        db = [data for data in datas]
        print(db)
        
    finally:
        #        
        cur.close()
        connect.close()

connectMysql()

2. 데이터베이스에 데이터 삽입
#!/user/bin/env python
#coding:utf-8
#Author:shenqiang

import pymysql

def connectMysql():
    try:
        '''     '''
        connect = pymysql.connect(
            host='127.0.0.1',
            user='root',
            password='shen6409175',
            db='students'
        )
    except Exception as  e:
        return e.args
    else:
        '''    '''
        cur = connect.cursor()
        '''    '''
        #        
        # sql = 'insert into student values(%s,%s,%s,%s);'
        # params = (6,' ~','24','  ')
        '''      '''
        sql = 'insert into student values(%s,%s,%s,%s);'
        params = [
            (7, '', '24', '  '),
            (8, '', '24', '  ')
            ]
        cur.executemany(sql,params)
        '''insert    commit()'''
        connect.commit()
    finally:
        #        
        cur.close()
        connect.close()

connectMysql()

 
3. 데이터베이스 삭제
#!/user/bin/env python
#coding:utf-8
#Author:shenqiang

import pymysql

def connectMysql():
    try:
        '''     '''
        connect = pymysql.connect(
            host='127.0.0.1',
            user='root',
            password='shen6409175',
            db='students'
        )
    except Exception as  e:
        return e.args
    else:
        '''    '''
        cur = connect.cursor()
        '''    '''
        sql = 'delete from student where id = %s'
        params = (7,)
        cur.execute(sql,params)
        '''      commit()'''
        connect.commit()
    finally:
        #        
        cur.close()
        connect.close()

connectMysql()

4. 완전한 Mysql 데이터 구동 방식
#!/user/bin/env python
#coding:utf-8
#Author:shenqiang
import pymysql

class MysqlTry:
    '''     '''
    def connectMysql(self):
        '''       '''
        try:
            connect =pymysql.connect(
                host = '127.0.0.1',
                user='root',
                password='shen6409175',
                db='students'
            )
        except Exception as e:
            print(e.args)
        return connect

    def selectMysql(self,sql,params):
        '''    '''
        cur = self.connectMysql().cursor()
        '''  '''
        cur.execute(sql,params)
        '''  '''
        result = cur.fetchone()
        return result

def checkValid(username,age):
    opera = MysqlTry()
    sql = "select * from student where name = %s and age = %s"
    params=(username,age)
    return opera.selectMysql(sql=sql,params=params)

def checkinfo():
    username = input('       
') age = input('
') result = checkValid(username,age) if result: print(' , !') else: print(' , bug!') if __name__ == '__main__': checkinfo()

셋.CSV 데이터 제어
1. csv 파일 내용을 취하는 방법
#!/user/bin/env python
#coding:utf-8
#Author:shenqiang
import csv

'''  csv     '''
def ReadCsvlist():
    '''   :       '''
#     '''      csv  '''
#     with open('csv.csv') as file:
#         '''reader csv    '''
#         reader = csv.reader(file)
#         '''    '''
#         next(reader)
#         '''     '''
#         db =  [item for item in reader]
#         return db
#
# print(ReadCsvlist(),type(ReadCsvlist()))
    ''''''
    with open('csv.csv',encoding='utf-8') as file:
        reader = csv.DictReader(file)
        for item in reader:
            print(dict(item))

ReadCsvlist()

오.DDT 테스트 드라이브
주의⚠️:같은 실행 절차가 있는 테스트 용례는ddt를 사용할 수 있습니다
1. 기본 소개
데이터 구동 테스트를 만들기 위해서는 테스트 클래스에 @ddt 장식부호를 사용하고 테스트 방법에 @data 장식부호를 사용해야 합니다. @데이터 장식부호는 파라미터를 테스트 데이터로 사용할 수 있습니다. 파라미터는 단일 값, 목록, 모듈, 사전일 수 있습니다. 목록과 모듈에 대해서는 @unpack 장식부호를 사용하여 모듈과 목록을 여러 개 파라미터로 해석해야 합니다.
#!/user/bin/env python
#coding:utf-8
#Author:shenqiang
import  csv
import  requests
import  ddt
import  unittest


url='https://www.lagou.com/jobs/positionAjax.json?needAddtionalResult=false'

def getHeaders():
   headers={
      'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
      'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
      'Cookie':'_ga=GA1.2.1237290736.1534169036; user_trace_token=20180813220356-b7e42516-9f01-11e8-bb78-525400f775ce; LGUID=20180813220356-b7e428ad-9f01-11e8-bb78-525400f775ce; index_location_city=%E5%85%A8%E5%9B%BD; _gid=GA1.2.675811712.1540794503; JSESSIONID=ABAAABAAAGFABEF93F47251563A52306423D37E945D2C54; _gat=1; LGSID=20181029213144-fa3c8e13-db7e-11e8-b51c-525400f775ce; PRE_UTM=; PRE_HOST=www.bing.com; PRE_SITE=https%3A%2F%2Fwww.bing.com%2F; PRE_LAND=https%3A%2F%2Fwww.lagou.com%2F; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1539529521,1539785285,1540794503,1540819902; SEARCH_ID=ae3ae41a58d94802a68e848d36c30711; Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1540819909; LGRID=20181029213151-fe7324dc-db7e-11e8-b51c-525400f775ce',
      'Referer':'https://www.lagou.com/jobs/list_%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95%E5%B7%A5%E7%A8%8B%E5%B8%88?labelWords=sug&fromSearch=true&suginput=%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95'}
   return headers

def f():
   list1=[]
   t=[i for i in range(1,31)]
   list1.append(t)
   return list1

@ddt.ddt
class LaGou(unittest.TestCase):
   @ddt.data((1,),(2,),(3,))
   @ddt.unpack
   def test_laGou(self,page):
      positions = []
      r = requests.post(
         url=url,
         headers=getHeaders(),
         data={'first': False, 'pn': page, 'kd': '        '})
      self.assertEqual(r.json()['success'],True)
      print(r.json()['content']['positionResult']['result'][0]['city'])

if __name__ == '__main__':
   unittest.main(verbosity=2)

2. DDT의 간단한 응용
#!/user/bin/env python
#coding:utf-8
#Author:shenqiang

from ddt import data,unpack,ddt
import unittest

@ddt
class MyDdtTest(unittest.TestCase):

    @data((1,1),(2,2),(3,3))
    @unpack
    def test_ddt(self,value1,value2):
        print('    {0},    {1}'.format(value1,value2))
        print(self.assertEqual(value1,value2))

if __name__ == '__main__':
    unittest.main(verbosity=2)

여섯.실행 로그 읽기 테스트
#!/user/bin/env python
#coding:utf-8
#Author:shenqiang

import  logging
from selenium import  webdriver
import  unittest

def log(log_content):
    #     
    logFile = logging.FileHandler('log.md', 'a',encoding='utf-8')
    # log  
    fmt = logging.Formatter(fmt='%(asctime)s-%(name)s-%(levelname)s-%(module)s:%(message)s')
    logFile.setFormatter(fmt)

    #     
    logger1 = logging.Logger('', level=logging.DEBUG)
    logger1.addHandler(logFile)
    logger1.info(log_content)

class Ui(unittest.TestCase):
    def setUp(self):
        self.driver=webdriver.Chrome()
        log('      ')

    def test_001(self):
        log('    ')
        pass

    def tearDown(self):
        log('    ')
        self.driver.quit()

if __name__ == '__main__':
    unittest.main(verbosity=2)

 










 
 
 
 
 

좋은 웹페이지 즐겨찾기