python mysql
import mysql.connector
from mysql.connector import Error, errorcode
import sys
#=================================================
class DB:
# 생성자
def __init__(self):
self.db_connect = None
self.cursor = None
# FUNC (1) instance method
"""
DB 서버 접근 메서드
"""
def MysqlDB_connect(self):
try: # DB에 접근 시도
self.db_connect = mysql.connector.connect(
user='root', password='1234',
host='127.0.0.1')
except Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print ("Something is wrong with your user name or password")
else:
print (err)
sys.exit(1)
else:
print ("MySQL server 접근 시도 성공")
self.cursur = self.db_connect.cursor()
# FUNC (2) instance method
"""
데이터 베이스(HEX_COLOR) 생성 인스턴스 메서드
"""
def DB_create(self):
temp_create_name = "HEX_COLOR"
sql = "CREATE DATABASE {}".format(temp_create_name)
try: # database 생성 시도
self.cursur.execute(sql)
except Error as err:
if err.errno == errorcode.ER_CANT_CREATE_DB:
print ("Database 생성 시도 실패")
else:
print (err)
sys.exit(1)
else:
print ("Database 생성 시도 성공".format(temp_create_name))
# FUNC (3) instance method
"""
데이터 베이스(HEX_COLOR) 접근 인스턴스 메서드
"""
def DB_access(self):
DB_access_name = "HEX_COLOR"
sql = "USE {}".format(DB_access_name)
try: # DB 접근 시도
self.cursur.execute(sql)
except Error as err:
if err.errno == errorcode.ER_BAD_DB_ERROR:
print ("접근하고자 하는 데이터베이스가 존재하지 않습니다.")
else:
print (err)
sys.exit(1)
else:
print ("{} 접근 시도 성공".format(DB_access_name))
# FUNC (4) instance method
"""
테이블 생성 인스턴스 메서드
"""
def Table_create(self):
create_table_name = "hex_color_url"
sql = "" \
"CREATE table {}(" \
" url_hex_color varchar(50) primary key" \
")".format(create_table_name)
try: # DB 접근 시도
self.cursur.execute(sql)
except Error as err:
if err.errno == errorcode.ER_CANT_CREATE_TABLE:
print ("테이블 생성 실패")
else:
print (err)
sys.exit(1)
else:
print ("{} 생성 시도 성공".format(create_table_name))
'언어 > python' 카테고리의 다른 글
hexcolor 사이트 python 크롤링 (0) | 2018.11.06 |
---|---|
사람인 크롤링 (version 2.3 - 2018-11-07) (2) | 2018.11.05 |
간단한 주말 프로젝트 (0) | 2018.11.03 |
카라바오 컵 파이썬 크롤링 (0) | 2018.11.01 |
맛집 크롤링 (0) | 2018.10.31 |
간단한 주말 프로젝트
# =======================================
from selenium import webdriver
from bs4 import BeautifulSoup
import mysql.connector
from mysql.connector import errorcode
import sys
import time
from bs4 import BeautifulSoup
# =======================================
class DBmysql:
# 생성자
def __init__(self):
self.conn_info = {
'user':'root', # user id
'password':'1234', # user pw
'host':'127.0.0.1', # mysql server ip address
'database':'college'
}
self.conn = None
self.cursor = None
# func (1) : 데이터 베이스 생성 > 테이블 생성
def serverConn(self):
try:
self.conn = mysql.connector.connect(
user=self.conn_info['user'],
password=self.conn_info['password'],
host=self.conn_info['host']
)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print ("계정 정보가 잘못된것 같습니다.")
else:
print (err)
sys.exit(1)
print ("[1] DB server connect success ... !!!")
self.cursor = self.conn.cursor()
# 데이터 베이스 생성
try:
sql = "CREATE DATABASE {}".format(self.conn_info['database'])
self.cursor.execute(sql)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_DB_CREATE_EXISTS:
print ("Database 생성 에러")
else:
print (err)
sys.exit(1)
else: # 데이터 베이스 생성 성공
print ("[2] 데이터 베이스 생성 성공")
try: # 데이터 베이스 접근 시도
self.cursor.execute('USE college')
except:
print ("DB 접근 실패")
else:
"""
c_name : 대학이름
l_name : 지역이름
"""
sql = "CREATE TABLE college_info (" \
" c_name varchar(30) PRIMARY KEY," \
" l_name varchar(30)" \
")"
try: # 테이블 생성 시도
self.cursor.execute(sql)
except:
print ("테이블 생성 시도 실패")
else:
print ("테이블 생성 성공")
self.conn.close()
def dataInsert(self, insrtv):
try:
# DB 접근
self.conn = mysql.connector.connect(
user=self.conn_info['user'], # user id
password=self.conn_info['password'], # user pw
host=self.conn_info['host'], # DB server ip address
database= self.conn_info['database'] # Database name
)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print ("접근 계정의 정보(id or pw)가 잘못된 것 같습니다.")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print ("접근 하고자 하는 DB 정보가 잘못된 것 같습니다.")
else:
print (err)
sys.exit(1)
else:
print ("DB 접근 성공 ...")
sql = "INSERT INTO `college_info`(c_name, l_name) VALUES (%s, %s)"
self.cursor = self.conn.cursor() # 객체 생성
for k, v in insrtv.items():
for i in v:
self.cursor.execute(sql, (i, k))
print ("DB 적재 성공 ...")
self.conn.commit() # 이 부분을 안하면 DB에 반영이 안된다.
class STU(DBmysql):
def __init__(self):
DBmysql.__init__(self) # 부모 클래스 초기화
self.webDriver = None
self.html = None
self.bsObj = None
self.local_colleges = {
"경기도":list(),
"강원도":list(),
"충청도":list(),
"전라도":list(),
"경상도":list(),
"제주도":list()
}
# func (1)
def seleniumDriv(self):
self.webDriver = \
webdriver.Chrome("C:\\Users\\sleep\\Desktop\\chrom_driver\\chromedriver.exe")
self.webDriver.get("https://www.naver.com/")
time.sleep(2) # 2 seconds ...
self.webDriver.find_element_by_id('query').send_keys("전국대학교")
time.sleep(2) # 2 seconds ...
self.webDriver.find_element_by_class_name("ico_search_submit").click()
'''
경기도 : //*[@id="main_pack"]/div[2]/div/div[2]/div[1]/ul/li[1]/ul/li[3]/a
강원도 : //*[@id="main_pack"]/div[2]/div/div[2]/div[1]/ul/li[1]/ul/li[4]/a
충청도 : //*[@id="main_pack"]/div[2]/div/div[2]/div[1]/ul/li[1]/ul/li[5]/a
전라도 : //*[@id="main_pack"]/div[1]/div/div[2]/div[1]/ul/li[1]/ul/li[6]/a
경상도 : //*[@id="main_pack"]/div[1]/div/div[2]/div[1]/ul/li[1]/ul/li[7]/a
제주도 : //*[@id="main_pack"]/div[1]/div/div[2]/div[1]/ul/li[1]/ul/li[8]/a
'''
local_dict = {
"경기도":[2, 3], "강원도":[2, 4], "충청도":[2, 5],
"전라도":[1, 6], "경상도":[1, 7], "제주도":[1, 8]
}
for k, v in local_dict.items():
btn = \
'//*[@id="main_pack"]/div[{}]/div/div[2]/div[1]/ul/li[1]/ul/li[{}]/a'.\
format(v[0], v[1])
self.webDriver.find_element_by_xpath(btn).click()
print ("current url: {}".format(self.webDriver.current_url))
self.html = self.webDriver.page_source
self.bsObj = BeautifulSoup(self.html, "html.parser")
time.sleep(2) # 2 seconds
element = self.bsObj.select("ul.lst_txt.no_dot > li > a")
for i in element:
print (i.text)
self.local_colleges[k].append(i.text)
time.sleep(2) # 2 seconds
self.dataInsert(self.local_colleges) # function call
def main():
node = STU() # 객체 생성
node.serverConn() # 테이블 생성
node.seleniumDriv() # 크롤링 데이터 수집
if __name__ == "__main__":
main()
=====================================================================================
from flask import Flask, request, render_template
import pymysql
conn = pymysql.connect(
host = "127.0.0.1",
user = "root",
password = "1234",
db = "college")
app = Flask(__name__)
@app.route("/")
def RootURL():
cursor = conn.cursor() # 객체 생성
sql = "SELECT * FROM college_info"
cursor.execute(sql)
results = cursor.fetchall()
return render_template('index.html', results=results)
if __name__ == "__main__":
app.run(host='0.0.0.0',
port=5555,
debug=True)
=====================================================================================
'언어 > python' 카테고리의 다른 글
사람인 크롤링 (version 2.3 - 2018-11-07) (2) | 2018.11.05 |
---|---|
python mysql (0) | 2018.11.04 |
카라바오 컵 파이썬 크롤링 (0) | 2018.11.01 |
맛집 크롤링 (0) | 2018.10.31 |
selenium - 테스트 코드 (0) | 2018.10.30 |
네이버 지식인 풀이, c언어 숫자 거꾸로 출력
https://kin.naver.com/qna/detail.nhn?d1id=1&dirId=1040101&docId=313575352
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# define LEN 40
# define ERROR 1
// ==========================
typedef struct Num {
char sNum[LEN]; // 문자열
int iNum; // 정수
}Num, *ptrNum;
// ============================
ptrNum newNode(); // func (1)
void Init(Num** p); // func (2)
void ValueInsert(Num** p); // func (3)
void ReversePrint(Num** p); // func (4)
// ============================
int main(void) {
ptrNum node = NULL;
node = newNode();
if (node == NULL) {
printf("malloc fail ...!!\n");
exit(ERROR);
}
else { // node != NULL
Init(&node);
ValueInsert(&node);
ReversePrint(&node);
}
free(node); // 메모리 해제
return 0;
}
ptrNum newNode() { // func (1)
ptrNum retNode = NULL;
retNode = (ptrNum)malloc(sizeof(Num));
return retNode;
} // end of newNode function
// ==============================
void Init(Num** p) { // func (2)
(*p)->iNum = 0;
strcpy((*p)->sNum, "\0");
} // end of Init function
// ==============================
void ValueInsert(Num** p) {
printf("정수 입력: ");
scanf("%d", &(*p)->iNum);
sprintf((*p)->sNum, "%d", (*p)->iNum);
//printf("%s\n", (*p)->sNum);
} // end of ValueInsert function
void ReversePrint(Num** p) {
int i; // index
int num = strlen((*p)->sNum)-1;
for (i = num; i >= 0; i--) {
printf("%c", (*p)->sNum[i]);
} printf("\n"); // 개행
} // end of ReversePrint function
'언어 > c언어' 카테고리의 다른 글
네이버 풀이 (0) | 2018.11.10 |
---|---|
네이버 지식인 풀이 (0) | 2018.11.07 |
네이버 지식인 풀이 (0) | 2018.10.14 |
네이버 지식인 풀이 링크드 리스트 (0) | 2018.10.13 |
네이버 지식인 문제 풀이 (0) | 2018.10.09 |
카라바오 컵 파이썬 크롤링
from selenium import webdriver
import requests
import pprint as ppr
import time
from bs4 import BeautifulSoup
import re
import openpyxl
from openpyxl.styles import Font, Alignment, PatternFill, Color
#===============================
class VISUAL:
def __init__(self):
self.wb = openpyxl.Workbook() # 객체 생성
self.ws = None # workSheet
self.excelIndex = [chr(i) for i in range(ord('B'), ord('I')+1)]
self.FristIndex = ['날짜', '경기시작_시간', '팀L', '점수', '-', '점수', '팀R', '경기장']
self.IndexWidth = [8.7, 13.2, 25, 8.1, 1.5, 8.1, 25, 17.2]
class SELEN:
def __init__(self):
# chrome driver
self.path = "C:\\Users\\sleep\\Desktop\\chrom_driver\\chromedriver.exe"
self.chrome_driver = webdriver.Chrome(self.path)
class STU(SELEN, VISUAL):
def __init__(self):
VISUAL.__init__(self)
SELEN.__init__(self)
# Instance variable
self.target_url = "https://www.naver.com/"
self.day_list = {"32강":['schedule_20180926',
'schedule_20180927',
'schedule_20181003 last'],
"16강":['schedule_20181101']}
self.html = None
self.bs_obj = None
self.information = {
"32강":[],
"16강":[]
}
# Instance method
# func (1)
def urlReguests(self):
self.chrome_driver.get(self.target_url)
time.sleep(2) # 2 second
# 검섹어 입력
self.chrome_driver.find_element_by_id('query').send_keys('카라바오컵')
self.chrome_driver.find_element_by_xpath('//*[@id="search_btn"]/span[2]').click()
time.sleep(2) # 2 second
"""
32강 : //*[@id="_calLayerBaseSportsDbSearch"]/div[2]/div/div[3]/ul/li[1]/a
16강 : //*[@id="_calLayerBaseSportsDbSearch"]/div[2]/div/div[3]/ul/li[2]/a
"""
# func (2)
def htmlURL(self):
tpage = {
"32강":1,
"16강":2
}
for key, p in tpage.items():
# 페이지 switch
tmp_bnt = '//*[@id="_calLayerBaseSportsDbSearch"]/div[2]/div/div[3]/ul/li[{}]/a'.format(p)
self.chrome_driver.find_element_by_xpath(tmp_bnt).click()
time.sleep(1)
self.html = self.chrome_driver.page_source
time.sleep(3)
self.bs_obj = BeautifulSoup(self.html, "html.parser")
# #강 - 날짜
t = [k for k in self.day_list[key]]
fnum = re.compile("\d{8}")
for i in t:
indx = fnum.search(i).span()
print(i[indx[0]:indx[1]], " : 작업 중 ...")
tmp_day_info = self.bs_obj.find_all("tr", {"class": i})
time.sleep(2)
for s in tmp_day_info:
# ==========================================
# 날짜
t_day = s.find("td", {'class': 'date tp4'})
t_day = t_day.string
# 시간
t_time = s.find("td", {'class': 'time tp4'})
t_time = t_time.string
# 경기장
t_stadium = s.select("p.elps > a")
t_stadium = t_stadium[0].attrs['title']
# left_team_infomation
left_team = s.select("td.score.mgn.tp4 > a.match > em.team_lft.team_lft2")
left_team = left_team[0].attrs['title']
# left_team_score
left_score = s.select("span.score_lft")
left_score = left_score[0].text
# right_team_infomation
rigth_team = s.select("td.score.mgn.tp4 > a.match > em.team_rgt.team_rgt2")
rigth_team = rigth_team[0].attrs['title']
# right_team_score
right_score = s.select("span.score_rgt")
right_score = right_score[0].text
# ==========================================
tmp_info = {
"날짜": None,
"경기 시작 시간": None,
"경기 결과": {
'LEFT':{
'Name':None,
'Score':None},
'RIGH':{
'Name': None,
'Score': None}},
"경기장": None}
tmp_info['날짜'] = t_day
tmp_info['경기 시작 시간'] = t_time
tmp_info["경기 결과"]['LEFT']['Name'] = left_team
tmp_info["경기 결과"]['LEFT']['Score'] = left_score
tmp_info["경기 결과"]['RIGH']['Name'] = rigth_team
tmp_info["경기 결과"]['RIGH']['Score'] = right_score
tmp_info['경기장'] = t_stadium
self.information[key].append(tmp_info)
def visualDo(self):
for k in self.information.keys():
self.ws = self.wb.create_sheet("CarabaoCup_"+k)
self.ws['B4'] = k
# Frist
num = 6
for i in zip(self.excelIndex, self.FristIndex, self.IndexWidth):
self.ws[i[0]+str(num)] = i[1]
self.ws.column_dimensions[i[0]].width = i[2]
num += 1
# Data insert
for element in self.information[k]:
inx = 0
# 날짜 데이터
self.ws[self.excelIndex[inx] + str(num)] = element['날짜'];inx += 1
# 시간 데이터
self.ws[self.excelIndex[inx] + str(num)] = element['경기 시작 시간']
self.ws[self.excelIndex[inx] + str(num)].alignment = \
Alignment(horizontal='center', vertical='center');inx += 1
# 팀 left ================================================
# 팀 이름
self.ws[self.excelIndex[inx] + str(num)] = \
element['경기 결과']['LEFT']['Name']
self.ws[self.excelIndex[inx] + str(num)].font = \
Font(color='87a8ee')
self.ws[self.excelIndex[inx] + str(num)].alignment = \
Alignment(horizontal='right', vertical='center');inx += 1
# 팀 score
# ========================================================
score_left = False
score_right = False
if element['경기 결과']['LEFT']['Score'] > element['경기 결과']['RIGH']['Score']:
score_left = True
elif element['경기 결과']['LEFT']['Score'] < element['경기 결과']['RIGH']['Score']:
score_right = True
# ========================================================
self.ws[self.excelIndex[inx] + str(num)] = \
str(element['경기 결과']['LEFT']['Score'])
self.ws[self.excelIndex[inx] + str(num)].alignment = \
Alignment(horizontal='right', vertical='center')
self.ws[self.excelIndex[inx] + str(num)].font = \
Font(bold=True)
if score_left:
self.ws[self.excelIndex[inx] + str(num)].font = \
Font(color="ca054d", bold=True)
self.ws[self.excelIndex [inx] + str(num)].fill = \
PatternFill(patternType='solid', fgColor=Color('d8d8d5'));inx += 1
self.ws[self.excelIndex[inx] + str(num)] = ":";inx += 1
# 팀 right ===============================================
# 팀 score
self.ws[self.excelIndex[inx] + str(num)] = \
str(element['경기 결과']['RIGH']['Score'])
self.ws[self.excelIndex[inx] + str(num)].font = \
Font(bold=True)
if score_right:
self.ws[self.excelIndex[inx] + str(num)].font = \
Font(color="ca054d", bold=True)
self.ws[self.excelIndex[inx] + str(num)].fill = \
PatternFill(patternType='solid', fgColor=Color('d8d8d5'));inx += 1
# 팀 이름
self.ws[self.excelIndex[inx] + str(num)] = \
element['경기 결과']['RIGH']['Name']
self.ws[self.excelIndex[inx] + str(num)].font = \
Font(color='87a8ee');inx += 1
self.ws[self.excelIndex[inx] + str(num)] = \
element['경기장'];
num += 1
def __del__(self):
self.wb.save("CarabaoCup.xlsx")
print ("excel 저장 성공")
def main():
stuNode = STU() # 객체 생성
stuNode.urlReguests()
stuNode.htmlURL()
stuNode.visualDo()
if __name__ == "__main__":
main()
'언어 > python' 카테고리의 다른 글
python mysql (0) | 2018.11.04 |
---|---|
간단한 주말 프로젝트 (0) | 2018.11.03 |
맛집 크롤링 (0) | 2018.10.31 |
selenium - 테스트 코드 (0) | 2018.10.30 |
pygame _ 연습2 (0) | 2018.10.27 |
# =================================
from selenium import webdriver
from bs4 import BeautifulSoup
from tinydb import TinyDB
import time
import pprint as ppr
# =================================
class DBstu:
# 생성자
def __init__(self):
# DB 생성
self.DB = TinyDB("eatList.db")
# 테이블 선택
self.user = self.DB.table("MOM")
class CWAL(DBstu):
# 생성자
def __init__(self):
DBstu.__init__(self)
# driver 위치
self.driver = webdriver.Chrome("C:\\Users\\sleep\\Desktop\\chrom_driver\\chromedriver.exe")
self.html = None
self.bsObject = None
self.titleList = []
# ============================
self.naverReq() # func call
# func (1)
def naverReq(self):
self.driver.get("https://www.naver.com/")
time.sleep(2) # 2초
self.driver.find_element_by_id("query").send_keys("부천 맛집")
self.driver.find_element_by_id("search_btn").click()
time.sleep(2) # 2초
# ============================
self.bsReq() # func call
# func (2)
def bsReq(self):
# //*[@id="place_main_ct"]/div/div/div[2]/div[4]/div/a[2]
page = 1
while True:
print("{0:02d}:page 작업 중 ...".format(page))
self.html = self.driver.page_source
self.bsObject = BeautifulSoup(self.html, "html.parser")
tmp = self.bsObject.find_all("div", {"class":"list_item_inner "})
""" tmp : list """
for i in tmp:
tmpDict = {}
n = i.select_one("div.info_area > div.tit > span.tit_inner > a.name")
p = i.select("div.info_area > div.etc_area.ellp > span.item")
r = '' # empty
# ========================
try:
result = p[1]
except:
pass
else:
r = result.text
finally:
time.sleep(3) # 3초
# ========================
tmpDict[n.attrs['title']] = r
self.titleList.append(tmpDict)
# page next
self.driver.find_element_by_xpath('//*[@id="place_main_ct"]/div/div/div[2]/div[4]/div/a[2]').click()
time.sleep(3)
if page == 20: break
else: page += 1
# ============================
self.dataPrintf() # func call
# func (3)
def dataPrintf(self):
for i in self.titleList:
for k, v in i.items():
self.user.insert({"가게이름":k, "가격":v})
print("가게 이름: {} , 가격: {} ... 적재 성공".format(k, v))
def main():
bsNode = CWAL() # 객체 생성
if __name__ == "__main__":
main()
'언어 > python' 카테고리의 다른 글
간단한 주말 프로젝트 (0) | 2018.11.03 |
---|---|
카라바오 컵 파이썬 크롤링 (0) | 2018.11.01 |
selenium - 테스트 코드 (0) | 2018.10.30 |
pygame _ 연습2 (0) | 2018.10.27 |
pygame _ 연습중 (0) | 2018.10.27 |
selenium - 테스트 코드
# ==================================
import selenium.webdriver as selWeb
import time
import cv2
from urllib.request import urlretrieve
# ==================================
class STU:
# 생성자
def __init__(self):
# 인스턴스 변수
self.webDriver = selWeb.Chrome("C:\\Users\\sleep\\Desktop\\chrom_driver\\chromedriver.exe")
# 인스턴스 메서드
def func01(self, searchData):
self.webDriver.get("https://www.google.co.kr/")
time.sleep(2) # 2+
self.webDriver.find_element_by_name('q').send_keys(searchData)
time.sleep(2)
self.webDriver.find_element_by_css_selector('input.lsb').click()
time.sleep(2)
# self.webDriver.find_element_by_xpath('//*[@id="hdtb-msb-vis"]/div[2]/a').click()
btn = self.webDriver.find_elements_by_css_selector('#hdtb-msb-vis > div > a')
btn[1].click()
# //*[@id="hdtb-msb-vis"]/div[2]/a
time.sleep(2)
img = self.webDriver.find_element_by_xpath('//*[@id="AiydHE6wkRVBlM:"]')
src = img.get_attribute('src')
urlretrieve(src, "mit.jpg")
def cv2ImageView(self):
self.webDriver.close()
img = cv2.imread('mit.jpg', 0)
cv2.imshow('mit', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
def main():
sNode = STU() # 객체 생성
sNode.func01("MIT")
sNode.cv2ImageView()
if __name__ == "__main__":
main()
'언어 > python' 카테고리의 다른 글
카라바오 컵 파이썬 크롤링 (0) | 2018.11.01 |
---|---|
맛집 크롤링 (0) | 2018.10.31 |
pygame _ 연습2 (0) | 2018.10.27 |
pygame _ 연습중 (0) | 2018.10.27 |
selenium + 자동화 + 네이버 메일 관리 부분 version 0.1 (0) | 2018.10.27 |
pygame _ 연습2
[+] MOUSEMOTION
import pygame as pg
pg.init()
# 화면 셋팅
out_screen = pg.display.set_mode((640, 400))
clock = pg.time.Clock()
dead_signal = False
bg_color = 0, 0, 0 # type of tuple
while not dead_signal:
for e in pg.event.get():
if e.type == pg.QUIT:
dead_signal = True
elif e.type == pg.MOUSEMOTION:
xPos, yPos = e.pos
pg.draw.line(out_screen,(255,255,255), (30, 250), (xPos, yPos))
pg.display.flip()
clock.tick(2)
'언어 > python' 카테고리의 다른 글
맛집 크롤링 (0) | 2018.10.31 |
---|---|
selenium - 테스트 코드 (0) | 2018.10.30 |
pygame _ 연습중 (0) | 2018.10.27 |
selenium + 자동화 + 네이버 메일 관리 부분 version 0.1 (0) | 2018.10.27 |
python - selenium + urllib (0) | 2018.10.26 |
pygame _ 연습중
import pygame as pg
pg.init()
# 화면
out_screen = pg.display.set_mode((840, 840))
clock = pg.time.Clock()
dead_signal = False
""" [x 축] """
posX = 0x0
""" [y 축] """
posY = 0x0
while not dead_signal:
for e in pg.event.get():
if e.type == pg.QUIT:
dead_signal = True
elif e.type == pg.MOUSEMOTION:
posX, posY = e.pos
print ("mouse at (%d, %d)"%e.pos)
if 250 <= posX <= 400 and \
250 <= posY <= 400:
print ("이벤트 발생")
pg.draw.rect(out_screen,(0, 255, 128), (posX, posY, 50, 50))
pg.display.update()
else:
out_screen.fill((0, 0, 0))
# out_screen.fill((0, 0, 0))
pg.display.flip()
clock.tick(2)
'언어 > python' 카테고리의 다른 글
selenium - 테스트 코드 (0) | 2018.10.30 |
---|---|
pygame _ 연습2 (0) | 2018.10.27 |
selenium + 자동화 + 네이버 메일 관리 부분 version 0.1 (0) | 2018.10.27 |
python - selenium + urllib (0) | 2018.10.26 |
pygrame01 (0) | 2018.10.24 |
selenium + 자동화 + 네이버 메일 관리 부분 version 0.1
import Database
import selenium.webdriver as selWeb
import time
from bs4 import BeautifulSoup
import re
#=======================================
class Center(Database.DB):
def __init__(self, url): # 생성자
Database.DB.__init__(self)
self.targetURL = url
# selenium
self.webDriver = selWeb.Chrome('C:\\Users\\sleep\\Desktop\\chrom_driver\\chromedriver.exe')
# naver_voice_number
self.naverVoiceNumber = ""
# filter
self.textFilter = re.compile("^새로운 기기\(브라우저\)에서 로그인 되었습니다.")
# func 01
def urlRequset_center(self):
self.webDriver.get(self.targetURL)
time.sleep(2) # 지연
self.webDriver.find_element_by_xpath('//*[@id="account"]/div/a/i').click()
time.sleep(2) # 지연
#ID / PW 값 넣기
self.webDriver.find_element_by_id('id').send_keys(self.usrInfo['id'])
self.webDriver.find_element_by_id('pw').send_keys(self.usrInfo['pw'])
self.webDriver.find_element_by_xpath('//*[@id="frmNIDLogin"]/fieldset/input').click()
time.sleep(2) # 지연
try:
# capcha 부분 자동 로그인 방지
self.webDriver.find_element_by_xpath('//*[@id="image_captcha"]/a[2]/span').click()
while not self.naverVoiceNumber:
self.naverVoiceNumber = input("number input : ")
self.webDriver.find_element_by_id('chptcha').send_keys(self.naverVoiceNumber)
self.webDriver.find_element_by_id('pw').send_keys(self.usrInfo['pw'])
self.webDriver.find_element_by_xpath('//*[@id="login_submit"]').click()
except:
# 등록/ 등록안함
self.webDriver.find_element_by_xpath('//*[@id="frmNIDLogin"]/fieldset/span[2]/a').click()
else:
# 등록/ 등록안함
self.webDriver.find_element_by_xpath('//*[@id="frmNIDLogin"]/fieldset/span[2]/a').click()
time.sleep(2)
# 메일 클릭
# selenium이 span 태그 제어 못함 그래서 find_element_by_link_text를 사용함
self.webDriver.find_element_by_link_text("메일").click()
# self.webDriver.find_elements_by_xpath('//*[@id="PM_ID_ct"]/div[1]/div[2]/div[1]/ul[1]/li[1]/a/span[2]').click()
time.sleep(2)
# 페이지 클릭
#
# //*[@id="normalPagingNav"]/span[1]/strong
# for p in range(2, 11):
# tmpHtml = self.webDriver.page_source
# tmpObject = BeautifulSoup(tmpHtml, 'html.parser')
# t = tmpObject.find_all('ul',{"class":"mInfo"})
for p in range(2, 11):
self.webDriver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
tmpHtml = self.webDriver.page_source
tmpObject = BeautifulSoup(tmpHtml, "html.parser")
# t = tmpObject.find_all('div', {'class':'mTitle'})
t = tmpObject.find_all('strong', {'class':re.compile("^mail_title")})
cunt = 0x0
for i in t:
if self.textFilter.search(i.text[6:]):
cunt += 1
print(cunt, " : ",i.text[6:], " : ", i.attrs['mailsn'])
self.webDriver.find_element_by_xpath('//*[@id="mailCheck_{}"]'.format(i.attrs['mailsn'])).click()
time.sleep(2)
# 이메일 삭제
self.webDriver.find_element_by_xpath('//*[@id="listBtnMenu"]/div[1]/span[2]/button[2]').click()
time.sleep(2)
# //*[@id="mailCheck_19085"]
# tempEmail = ""
# j = i.find("div", {'class':'name _ccr(lst.from) '})
# tempEmail += j.text
#
# j = i.find("div", {'class':'subject'})
# tempEmail += j.text
# print (tempEmail)
# if self.textFilter.findall(tempEmail):
# checkBox = tmpObject.find_all('ul', {"class": "mInfo"})
# tempV = [i.select_one('input') for i in checkBox]
# print ("=========> {}".format(tempV))
self.webDriver.find_element_by_link_text("{}".format(p)).click()
time.sleep(4)
def main():
sNode = Center("https://www.naver.com/")
sNode.urlRequset_center()
if __name__ == "__main__":
main()
'언어 > python' 카테고리의 다른 글
pygame _ 연습2 (0) | 2018.10.27 |
---|---|
pygame _ 연습중 (0) | 2018.10.27 |
python - selenium + urllib (0) | 2018.10.26 |
pygrame01 (0) | 2018.10.24 |
selenium + 잡코리아 크롤링 + openpyxl (0) | 2018.10.24 |
python - selenium + urllib
# =======================================
import selenium.webdriver as selWeb
import urllib.request as urlReq
import time
from bs4 import BeautifulSoup
# =======================================
class STU01(object):
# 생성자
def __init__(self, url):
# Instance variable
self.webDriver = selWeb.Chrome(
'C:\\Users\\sleep\\Desktop\\chrom_driver\\chromedriver.exe'
)
self.targetUrl = url
self.html = None
# BeautifulSoup
self.bsObject = None
# save img_file
self.saveImg = "harry_potter.jpg"
"""
영화 : #PM_ID_themelist > ul > li:nth-child(12) > a
방향 이동 : //*[@id="PM_ID_themecastNavi"]/div[2]/a[2]
"""
# FUNC (1)
def reqURL(self):
self.webDriver.get(self.targetUrl)
time.sleep(4)
while True:
try:
self.webDriver.find_element_by_xpath('//*[@id="PM_ID_themelist"]/ul/li[12]/a').click()
time.sleep(2)
except:
self.webDriver.find_element_by_xpath('//*[@id="PM_ID_themecastNavi"]/div[2]/a[2]').click()
time.sleep(4)
else:
break
self.html = self.webDriver.page_source
self.bsObject = BeautifulSoup(self.html, "html.parser")
img_data = self.bsObject.select_one('#PM_ID_themecastBody > div > div > div > ul > li.tl_bigimage > a > div.tb_mw > img')
urlReq.urlretrieve(img_data.attrs['src'], self.saveImg)
print ("Image save success ...")
def main():
stCrawling = STU01("https://www.naver.com/")
stCrawling.reqURL()
if __name__ == "__main__":
main()
'언어 > python' 카테고리의 다른 글
pygame _ 연습중 (0) | 2018.10.27 |
---|---|
selenium + 자동화 + 네이버 메일 관리 부분 version 0.1 (0) | 2018.10.27 |
pygrame01 (0) | 2018.10.24 |
selenium + 잡코리아 크롤링 + openpyxl (0) | 2018.10.24 |
python - 크롤링 - matplotlib - pie 차트 조합 (0) | 2018.10.21 |