웹크롤링 핵심인 웹element 식별. 그중에 Xpath에 대해 좀더 알아보자

XPATH 의미
./li 현재 태그의 바로 하위에 있는 li 태그
../li 바로 상위에 있는 태그의 하위에 있는 li 태그
//li 문서 전체 중 모든 li태그
//li//ul 문서 전체 중 모든 li 태그의 하위에 있는 모든 ul 태그
//li[@id='myid'] 문서 전체 중 id 속성이 'myid'인 li태그
//*[@id='myid'] 문서 전체 중 id 속성이 'myid'인 모든 태그
//input[@class!='myclass'] 문서 전체 중 class 속성이 'myclass'가 아닌 input 태그
//a[text() = '2'] 문서 전체 중 태그 내용이 '2' 인 a 태그
//a[contains(text(), '다음')] 문서 전체 중 태그 내용에 '다음' 이 포함되는 a 태그
//a[contains(@id,'this')] 문서 전체 중 id 속성에 'this'가 포함된 a 태그
//a[starts-with(@id, 'this')] 문서 전체 중 id 속성이 'this'로 시작되는 a 태그
//a[@class='myclass' and contains(text(), '제목')] 위의 조건을 2개 이상 요구할 경우 and 로 나열한다.
//a[@class='myclass' or contains(text(), '제목')] 위의 조건(2개 이상) 중 1개만 만족해도 된다면 or 로 나열한다

# Expected_conditions에 정의된 조건 목록(페이지 로딩 소요에 따른 이벤트 처리)

from selenium.webdriver.support import expected_conditions as EC
로 먼저 import 한다.

조건 클래스 의미 예시
title_is 웹사이트 제목이 특정 문자열과 일치 여부 확인 EC.title_is('네이버')
title_contains 웹사이트 제목에 특정 문자열 포함 확인 EC.title_contains('네이')
url_conditions 웹사이트 url(주소)에 특정 문자열 포함 확인 EC.url_contains('account')
visibility_of_element_located 특정 태그의 화면에 표시여부 확인 EC.visibility_of_element_located(By.ID, 'spec_id')
text_to_be_present_in_element 특정 태그 내용에 특정 문자열 포함 확인 EC.text_to_be_present_in_element_value(By.ID, 'spec_id'), '특정문자열')
element_to_be_clickable 특정태그 클릭가능 확인 EC.element_to_be_clickable(By.ID, 'spec_id')

# 파이썬에도 Thread(쓰레드)가 존재한다.#

try :
	t = Thread(target=함수명, args=(param1, param2..))
    t.start()
except Exception as e :
	pass #무시

위 처럼 except로 예외문에 대해서, print(e)를 출력해서 확인해도 내용 파악이 어렵다면, sys 모듈의 exc_info()함수를 호출해서 확인할 수도 있다.

import sys
try : 
	1/0
except :
	err = sys.exc_info()
    for e in err :
    	print(e)

# 자바처럼 생성자를 만들수 있다. __init()__.#

파이썬도 클래스를 생성할 수 있는데, 자바처럼 생성할때 인자를 받거나, 초기 작업을 하는 것은 선택적이다. 만약 초기작업이 필요하면, 아래와 같이, 클래스 안에 init함수를 선언하면 된다. 그리고 enter와 exit는 클래스 입장/퇴실할 때 호출되는 함수인데, 반복되는 내용을 입력하면 자동호출된다.
*클래스안에서 메소드 및 멤버 변수를 이용할 때, 반드시 self를 추가하지만, 이용할 때는 붙이지 않는다.

class Usedatabase :
	def __init__(self, config : dict) -> None :
    	self.configuration = config
        
    def __enter__(self) -> 'cursor' :
    	self.conn = mysql.connector.connect(**self.configuration)
        self.cursor = self.conn.cursor()
        return self.cursor
    
    def __exit__(self, exc_type, exc_value, exc_trace) -> None:
    	self.conn.commit()
        self.cursor.close()
        self.conn.close()

# 파일을 읽는 때는 with 절을 이용하세요. #

with open('vstart.log') as log :
	contents = log.read()

일반적으로 파일을 open('vstart.log', 'r') 로 읽어도 좋지만, with 문과 함께 쓴다면, 종료시 file.close()를 하지 않아도 자동으로 닫아준다. 큰 프로젝트가 아니라면 문제되지 않으나 개발자의 실수를 커버해주는 좋은 코딩 습관이다.

Posted by 목표를 가지고 달린다
,