일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- pywinauto
- Uipath 기초
- pywinauto 윈도우제어
- 파이썬 가상환경 설치
- 네이버커머스API
- pywinauto 윈도우
- 파이썬 환경설정
- 파이썬 가상환경 설치방법
- 네이버 로그인 영수증 해결
- 날짜 정규식
- Python
- Uipath 설치방법
- 왕초보 파이썬 실행
- selenium
- UiPath
- 가상환경설치
- Selenium 셀렉터잡기
- vscode venv 설치
- 파이썬네이버부동산
- Element is not clickable at point
- 네이버부동산크롤링
- 네이버매물크롤링
- 네이버 로그인 하기
- 파이썬 네이버 로그인
- pycdc.exe
- 네이버 로그인 캡챠해결
- venv 설치
- uipath 입문
- 커머스API
- pycdas.exe
- Today
- Total
목록프로그래밍 (351)
콘솔워크
# 오류 발생 시 프로그램 강제종료 방지 def my_exception_hook(exctype, value, traceback): print(exctype, value, traceback) global_log_append(str(value)) sys._excepthook(exctype, value, traceback) sys.excepthook = my_exception_hook
call-by-value (값을 복사해서 사용) 해당 방식은 함수를 호출할 때 전달되는 변수의 값을 복사하여 함수의 인자로 전달된다. 복사된 인자는 함수 안에서 사용되는 local value의 특성을 가진다. 따라서 함수 안에서 인자의 값이 바뀌어도, 외부 변수의 값은 변경되지 않는다. call-by-reference (값을 직점 참조) 함수가 호출되면, 메모리에 함수를 위한 임시공간이 생성되고, 함수가 종료되면 그 공간은 사라진다. 해당 방식은 함수 호출시 인자로 전달되는 변수의 주소를 전달한다. 따라서 인자의 값이 변경되면, 전달된 객체의 값도 변경된다. call-by-assignment (파이썬의 방식) 파이썬의 경우에는 call-by-assignment 방식을 사용한다. 파이썬에서는 모든 것이 객..
dataframe을 이용하여 query를 하려고 하는데, 데이터 안에 문자형이 들어가 있어서 Type Error가 나왔다. 오류메시지 TypeError: '>' not supported between instances of 'str' and 'int' 이럴때는 datafame 안에 원하지 않는 값 (숫자가 아닌 값을 필터링 하는 작업이 필요하다) df_ad_result = df_ad_result[ pd.to_numeric(df_ad_result["monthlyMobileQcCnt"], errors="coerce").notnull() ] 이렇게 해주면 데이터 유효성을 통한 필터링이 가능하다. 그 후에 query를 진행한다. str_expr = "(monthlyMobileQcCnt > 3000)" # 나이가..
from PyQt5.QtWidgets import * from PyQt5 import QtWidgets, QtCore, QtGui from PyQt5.QtCore import * from PyQt5.QtGui import * class MainUI(QDialog): def __init__(self): super().__init__() self.setWindowFlags(Qt.WindowCloseButtonHint | Qt.WindowMaximizeButtonHint | Qt.WindowMinimizeButtonHint)
1. 스마트폰과 연결하기 위해 구글 개발자 페이지에서 adb (android device bridge)를 설치합니다. https://developer.android.com/studio/releases/platform-tools?hl=ko#downloads SDK 플랫폼 도구 출시 노트 | Android 개발자 | Android Developers Android SDK 플랫폼 도구는 Android SDK의 구성요소입니다. developer.android.com 1-1. 윈도우 환경변수에 해당 폴더 추가 2. 자신의 파이썬 작업환경에서 pure-python-adb를 설치합니다. pip install pure-python-adb 3. 안드로이드 스마트폰에서 개발자모드 활성화 및 USB 디버깅 모드 허용 위 작..
# str로 되어있는 날짜 start_date = '2022-01-01' # 위의 형식에 맞게 날짜로 형변환 start_date = datetime.strptime(start_date, f'%Y-%m-%d') # QDateEdit에 넣기 위해 QDate로 형변환 Q_start_date = QDateEdit(QDate(start_date))
my_list = ['1', '1', '1', '2', '3', '4', '4', '5', '6'] if len(my_list) == 0: print(f"결과가 없습니다.") else: print(f"{my_list}") print(f"{len(my_list)}") for el1, el2 in zip(my_list, my_list[1:]): if el1 == el2: print(el1, el2) my_list.remove(el1) print(f"{el1} 제거") my_list = list(set(my_list)) print(f"중복 제거 후 {len(my_list)}개의 주소") print(my_list)
현재 vscode에서 작업 시 멀티 스레드 상의 디버깅 중단점이 안먹는 경우가 있다. 위 경우에 코드 몇줄을 추가해주면 중단점이 먹는 경우가 있다. import debugpy debugpy.debug_this_thread() 디버깅 기술문서에는 코드의 최상단의 위 코드를 추가해주면 된다고 하였지만 작동하지 않았고 디버깅 포인트와 같은 레벨의 함수에 debugpy.debug_this_thread()를 추가해주니 정상 작동 하였다.
if 1 == 1: import sys import os sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) import urllib.request class APIPracticeBot: def __init__(self) -> None: self.client_id = "" self.client_secret = "" self.url = "https://openapi.naver.com/v1/search/book?query=" def my_client_info(self): print(f"{self.client_id} {self.client_secret}") def get_search_url(self, keyword=""): ..
key = "hi" value = "안녕" # 출력결과 >> hi 안녕 print(f"{key} {value}") dict_hello = {} dict_hello[key] = value # 출력결과 >> {'hi': '안녕'} print(dict_hello) # 출력결과 >> 안녕 print(dict_hello["hi"]) key와 value를 넣고 key로 호출하는 법
import re my_date = None file_names = f"발주정보[123](2022-07-07)[test](괄호안문자)[나는대괄호문자]-거래처코드임시변경.xlsx" # 대괄호안에 들어있는 문자들을 추출해 리스트에 담는다 # ['123', 'test', '나는대괄호문자'] bracket_pattern = r"\[([^]]+)" file_names = re.findall(bracket_pattern, file_names) print(f"{file_names}")
try: error_alert = driver.switch_to.alert time.sleep(1) alert_text = error_alert.text print(f"{alert_text}") error_alert.accept() if alert_text.find("에러메시지_1") > -1: raise Exception(f"{alert_text}") elif alert_text.find("에러메시지_2") > -1: raise Exception(f"{alert_text}") elif len(alert_text) > 0: raise Exception(f"{alert_text}") except NoAlertPresentException: print("alert가 없습니다.") pass except Exc..
print(df) # a # 0 aa # 1 ba # 2 ca print(df[df['a'].isin(['aa', 'ca'])]) # a # 0 aa # 2 ca print(df[df['a'].str.contains('b')]) # a # 1 ba 위와 같이 데이터를 필터링하는 용도로 사용할 수 있다. isin()의 경우에는 부분일치를 사용할 수 없지만 다른 데이터 타입에도 적용 할 수 있는 특징이 있고, str.contains()는 오로지 string에만 사용 할 수 있다.
객체의 복사에는 deep 이라는 옵션이 있다. # 원본 df_normal = pd.DataFrame() # 깊은 복사 df_deep = df_normal.copy(deep=True) # 얕은 복사 df_shallow = df_normal.copy(deep=False) df_deep의 경우에는 깊은 복사를 의미 하고 원본 데이터프레임(df_normal)의 값이 바뀌더라도 해당 데이터프레임(df_deep)의 값은 변하지 않는다. 즉, 서로에게 영향을 끼치지 않는 복사이다. df_shallow의 경우에는 얕은 복사를 의미 하고 원본 데이터프레임(df_normal)과 자료를 실시간으로 공유하게 된다. (이 경우 df_shallow에서 변하게 된 값도 원본인 df_normal에도 적용된다.)
from selenium.webdriver.chrome.options import Options from selenium import webdriver def get_chrome_driver_new(): options = Options() # 파라미터에 다운로드 경로를 지정 options.add_experimental_option("prefs", {"download.default_directory": r"C:\excels"}) driver = webdriver.Chrome(f"./{chrome_ver}/chromedriver.exe", options=options) driver.implicitly_wait(30) # 페이지가 로딩될 때 까지 10초동안 대기 driver.set_page_load_timeo..
python을 이용하여 apscheduler를 쓰는데, 특정 시간 대에만 스케쥴 작업이 필요하였다. add_job을 여러개 등록하면, 랜덤하게 시작되는 현상이 있어서 add_job에 CronTrigger를 여러개 등록하는 방식으로 하니까 잘 되었다. CronTrigger들은 OrTrigger로 묶어서 진행하면 된다. from apscheduler.triggers.combining import OrTrigger from apscheduler.triggers.cron import CronTrigger from apscheduler.schedulers.background import * class Thread30min(QThread): def __init__(self): super().__init__() se..
import win32com.client as win32 def xlsx_to_xls(source): if not str(source).find("xlsx") > -1: return if not os.path.isfile(source): return excel = win32.gencache.EnsureDispatch("Excel.Application") wb = excel.Workbooks.Open(source) xls_file = source[:-1] if os.path.isfile(xls_file): os.remove(xls_file) wb.SaveAs(xls_file, FileFormat=56) # FileFormat = 51 is for .xlsx extension wb.Close() # File..
# 작은 따옴표 안의 문자 re.findall("'([^']*)'", your_string) # 큰 따옴표 안의 문자 re.findall('"([^"]*)"', your_string) 사용 사례 js = javascript:goDelvTrack('111111','한진택배','222222222222','https://www.hanjin.co.kr/kor/CMS/DeliveryMgr/WaybillResult.do?mCode=MN038&schLang=KR&wblnumText2=222222222222','33333333333333') js_splits = re.findall("'([^']*)'", js) print(js_splits) # 결과 ['111111', '한진택배', '222222222222', 'ht..
데이터 프레임의 특정 열에 아래와 같은 문장이 들어있다. "apple is delicious" "banana is delicious" "apple and banana both are delicious" 지금까지 사용했던 필터링 방식인 contains와 '|' 연산자를 사용한다면 아래와 같은 결과가 나온다. df.col_name.str.contains("apple|banana") # 결과 "apple is delicious", "banana is delicious", "apple and banana both are delicious" 이번 상황에서는 마지막줄에 있는 "apple and banana both are delicious"만을 필터링 하고 싶은데 이런 상황에서 사용 할 수 있는 몇가지 방법이 있다..
# 스프레드 시트 def goods_spreadsheet(url): gc = connect_json() spreadsheet = gc.open_by_url(url) return spreadsheet # 각 worksheet 조회 def get_goods(worksheet): datas = worksheet.get_all_values(value_render_option="FORMULA") # 수식을 그대로 불러오는 파라미터 옵션 datas = datas[1:] datas = pd.DataFrame(datas[1:], columns=datas[0]) # print(datas) return datas if __name__ == "__main__": goods_url = "https://docs.google.c..
1. 숫자를 1개의 문자열로 추출 (String) import re message = "asdfasdf1234, TYTRHdf567890,dgk" message = re.sub(r"[^0-9]", "", message) print(message) # 1234567890 2. 이어져있는 숫자끼리 나눠서 추출 (List) import re message = "asdfasdf1234, TYTRHdf567890,dgk" message = re.findall(r'\d+', message) print(message) # ['1234', '567890'] 3. 숫자를 한 글자씩 분리하여 추출 (List) import re message = "asdfasdf1234, TYTRHdf567890,dgk" message =..
from datetime import timedelta # 현재 날짜 today = datetime.today() # 현재 년도, 월, 일, 시간 current_year = datetime.today().year current_month = datetime.today().month current_day = datetime.today().day current_hour = datetime.today().hour # 어제, 내일 yesterday = datetime.today() - timedelta(1) tomorrow = datetime.today() + timedelta(1) # 날짜 표기 형식 변경 -> YYYY.mm.dd HH:MM:SS today = datetime.today().strftime(f..
# 처방 def get_df_prescribed(self): df_prescribed = self.df_order.loc[self.df_order["처방구분"].str.match("처방")] print(df_prescribed) return df_prescribed # 비처방 def get_df_not_prescribed(self): df_not_prescribed = self.df_order.loc[self.df_order["처방구분"].str.match("비처방")] print(df_not_prescribed) return df_not_prescribed contains로는 겹쳐버리는 문자가 있으면 걸러내지 못하는 데이터를 match를 이용해서 걸러낸다.
driver.set_page_load_timeout(360) 웹 드라이버를 호출할 때 위의 괄호 안에 초단위의 시간을 적어주면 된다. selenium이 기다려주는 최대 시간을 뜻하는 것 같다.
Windows에서 Visual Studio 설치 후 Decompyle++ 깃허브 자료를 이용하여 exe파일을 만들었습니다. 깃허브 주소는 https://github.com/zrax/pycdc 입니다. exe 파일 필요하신 분은 댓글 남겨주세요. pycdas.exe pycdc.exe
일전에 사용했던 칼럼에 특정 단어가 포함 되어있는 지를 검증하는 코드를 활용했다. new_df = df.loc[df['칼럼1'].str.contains('단어1|단어2')] 검증하고싶은 list를 위의 contains안에 들어가도록 형태를 바꿔야 한다. my_list = ['단어1', '단어2', '단어3'] # my_list를 포함하는 경우 new_df = df.loc[df['칼럼1'].str.contains("|".join(my_list))] # my_list를 포함하지 않는 경우 new_df2 = df.loc[~df['칼럼1'].str.contains("|".join(my_list))] 끝
원래 사용하는 것은 환경변수 path 에있는 파이썬 기본 값으로 만든다. python -m venv venv 특정버전으로 하고 싶으면 아래와 같이 하면 된다. py -[버전] -m venv [venv명] 3.6버전으로 하고 싶으면 이렇게 py -3.6 -m venv venv36 하고싶은 버전이 없다면 컴퓨터에 해당 버전이 먼저 설치되어 있어야한다.
set의 difference() 이용 self.success_list = list(set(self.success_list).difference(self.failed_list)) list를 set으로 변환하여 연산 후 다시 list로 변환 self.success_list = list(set(self.success_list) - set(self.failed_list))
이렇게 상품이 있고, 상품명과 일치하는 input 엘리먼트에 값을 입력하고 싶을 때 사용한다. product_name에 상품명 입력 product_name = "본에정 300T" order_count = "5" driver.find_element( By.XPATH, f'//li[.//p[text()="{product_name}"]]//input[@name="pd_order"]' ).send_keys(order_count)
특정 텍스트를 입력받아 xpath를 찾았는데, selenium으로 조회는 가능했지만 클릭이 불가능 했던 상황에 사용한 코드 goods = driver.find_element( By.XPATH, f'//div[text()="{your_text}" and contains(@class, "option")]' ) print(goods) # web element driver.execute_script("arguments[0].click();", goods) time.sleep(0.5)