프로그래밍 351

python html에서 원하는 태그만 추출하기

beautifulsoup4 라이브러리를 설치한다. pip install beautifulsoup4 from bs4 import BeautifulSoup html_file = r"__test__\article_sample.html" page = open(html_file, "rt", encoding="utf-8").read() # HTML 파일 읽고 문자열 리턴 soup = BeautifulSoup(page, "html.parser") # Soup 객체 생성 # div와 p 두 종류가 있음 for div in soup.find_all(["div", "p"]): print(div) beautifulsoup4 라이브러리를 사용하면 html을 쉽게 파싱할 수 있다. fild_all 함수를 이용하여 원하는 태그만..

python 날짜 n월 n주차 구하기

규칙 1. 주의 시작은 월요일이다. 2. 월~일 까지 중 월이 다른 경우 어느 월을 선택할지 기준은 더 많은 쪽을 선택하면 된다. 3. 따라서, 더 많은 쪽을 나누는 기준은 "목요일"이다. 예를들어, 위의 규칙으로 2023년 5월 30일은 몇주차 일까? 6월 1주차일까 5월 5주차일까? 정답은 6월 1주차이다. 왜냐하면 목요일이 6월달이기 때문이다. from datetime import datetime, date, timedelta import lunardate import calendar import numpy as np last_day_of_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] leap_year_last_day_of_month = [31..

selenium이나 request로 크롤링을 하는 중 차단을 당한 경우 우회하는 방법 중 하나

pip install random_user_agent #!/usr/bin/env python if 1 == 1: import sys import os sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) from random_user_agent.user_agent import UserAgent from random_user_agent.params import SoftwareName, OperatingSystem class RandomUserAgentTest: def __init__(self): self.get_headers() print(self.headers) def set_user_agent(self): softwar..

python 인터페이스 만들기

사실 파이썬은 interface 를 단어 그 자체로서 존재하고 지원하는 언어는 아닙니다. 다만, https://peps.python.org/pep-3119/ 를 읽어보면 알 수 있듯이 추상 메서드와 같은 인터페이스 비슷한 문법을 제공합니다. python 웹 스크래퍼 작성 중, 필히 구현되어야 하는 메서드들을 한데 묶어두고 관리해야 할 필요성을 느껴 인터페이스를 만들게 되었습니다. ( - 사실 best practice 인지는 모르겠습니다.) from abc import ABC, abstractmethod class BaseScrapper(ABC): """ 모든 스크래퍼의 기본 스크래퍼입니다. 해당 클래스를 상속받는 클래스는 아래의 메서드를 필수로 구현해야 합니다. """ @abstractmethod def..

pyqt5 -> pyside6로 변경할 시 주의할 점

기본적으로 변경할 때, PyQt5로 되어있는 import만 PySide6로 변경하면 바로 사용이 가능하지만, 몇가지 손을 봐야하는 경우가 있음. # PyQt5 cp = QDesktopWidget().availableGeometry().center() # Pyside6 cp = QGuiApplication.primaryScreen().availableGeometry().center() # PyQt5 @pyqtSlot() # Pyside6 @Slot() # PyQt5 pyqtSignal() # Pyside6 Signal() 시그널 및 슬롯의 구문을 그대로 사용하는 것은 가능하지만, import 해야하는 구문이 달라지기 때문에 그에 맞게 변환해주어야 작동한다. # PyQt5 from PyQt5.QtCore i..

dataframe의 자료를 query문을 사용해서 필터링 하는 방법

def get_df_filtered(self, df_result: pd.DataFrame): query_string = f"(열1 > {변수1}) and (열2 > {변수2}) or (열3 > {변수3}) not (열4 > {변수4})" print(f"query_string: {query_string}") df_filtered = df_result.query(query_string) return df_filtered 비교 연산자, 논리 연산자와 같은 연산자를 변수로 받아와서 사용하는 것도 가능하기 때문에 df.loc[]보다 유용하게 사용할 수 있다.