Python/Python__works

selenium tutorial

말하는감자 2019. 11. 8. 14:19
from bs4 import BeautifulSoup
from selenium import webdriver

class Selenium(object):
	
	def __init__(self)
		
		#서버에서 사용하기 위한 headless 
		options = webdriver.ChromeOptions()
		options.add_argument('--headless')
		options.add_argument('--no-sandbox')
		options.add_argument('--disable-dev-shm-usage')
		options.add_argument('--disable-gpu')
		
		try: #for server
			self.driver = webdriver.Chrome(executable_path='서버path', chrome_options=options)
		except: #for local
			self.driver = webdriver.Chrome(executable_path='로컬 크롬드라이버 path ')
		
	def first_page(self):
		try:
			#스크래핑할 화면 접근
			self.driver.get("사이트 주소")
			time.sleep(2) #페이지 로딩을 위해서 잠시 기다려준다
			#self.driver.implicitly_wait(2)로 페이지가 draw 되는것을 기다릴 수 있지만
			#ajax로 호출해서 느리게느리게 가져오는 사이트의 경우에는 원하는대로 동작하지 않기 때문에
			#time.sleep으로 시간을 준다
			
			self.driver.find_element_by_xpath('').click() #click
			self.driver.find_element_by_xpath('').send_keys('입력할 값') #form 등에 입력할때
			
			#BTN을 click했지만 click 이벤트가 먹지 않는경우 ENTER로 컨트롤 
			self.driver.find_element_by_xpath('').send_keys(Keys.ENTER)
			
			#selenium으로 element가 있는지 확인해서 하는 방법도 있지만
			#웬지 원하는대로 잘 동작하지 않았다
			#해당 값이 html에 들어있는지 확인한 후에 분기문을 태워서 조작하는 방법이 좀더 쉽다
			req = self.driver.page_source
			soup = BeautifulSoup(req, 'html.parser')
			html = soup.select('') #findAll등을 사용해도 무방하다
			
			btn_chk = soup.findAll('div', attrs={'style': 'display_none;'} #숨겨진 div 확인
			
			if btn_chk: #div가 숨겨져 있다면
				#원하는 액션
			else:
				#원하는 액션
			
			#원하는 액션이 종료되었다면 반드시 종료해주어야 한다
			self.driver.quit()
		except Exception as e:
			self.driver.quit()
			print(e)

'Python > Python__works' 카테고리의 다른 글

asyncio  (0) 2019.11.19
파이참 터미널에서 pip upgrade해도 버젼 안바뀌거나 오류날때  (0) 2019.11.13
python + shell script  (0) 2019.10.22
lambda  (0) 2019.10.17
문자열 치환하기  (0) 2019.10.11