[selenium 함수]

함수

설명

webdriver.Chrome("c:/...")

chrome driver가 설치된 위치 지정하여 사용

implicitly_wait(3)

암묵적으로 모든 웹 자원 로드를 위해 3초 기다림

get(http://url.com’)

url에 접근

page_source

현재 렌더링 된 페이지의 Elements를 모두 가져오기

find_element_by_name('...’)

페이지의 단일 element중 name으로 접근

find_element_by_id('HTML_id’)

id로 접근

find_element_by_xpath(‘xpath’)

xpath로 접근

find_element_by_css_selector(‘...’)

css selector로 접근

find_element_by_class_name('...’)

class 이름으로 접근

find_element_by_tag_name('...’)

tag name으로 접근

close

사용했던 chrome driver 닫기


[사용 예시]


1. 네이버 로그인 하기(2019/02/20 기준 차단된 사용법)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from selenium import webdriver
from bs4 import BeautifulSoup as bs
import time
 
# chromedriver의 위치 지정
driver = webdriver.Chrome("c:/Users/학습러/Desktop/chromedriver_win32/chromedriver.exe")
 
login_url = "https://nid.naver.com/nidlogin.login"
driver.get(login_url)
 
driver.find_element_by_id("id").send_keys("myid"# id 넣기
driver.find_element_by_id("pw").send_keys("password"# password 넣기
 
# 로그인 클릭
driver.find_element_by_xpath('//*[@id="frmNIDLogin"]/fieldset/input').click()
 
time.sleep(2)
driver.close()
 
## 2019/02/20 기준 send_keys 함수 사용하면 
## 네이버가 자동화된 소프트 웨어라 판단하고 막아놓음
cs

위의 코드 실행시,

현재는 막혀있기 때문에 이와같이 로봇인지 사람인지 구분하는 페이지로 넘어간다.


2. 네이버 로그인 하기(우회 접근)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from selenium import webdriver
from bs4 import BeautifulSoup as bs
import time
 
# chromedriver의 위치 지정
driver = webdriver.Chrome("c:/Users/학습러/Desktop/chromedriver_win32/chromedriver.exe")
 
login_url = "https://nid.naver.com/nidlogin.login"
driver.get(login_url)
 
## 네이버 로그인 우회 
 
id = "my_id"
pw = "my_password"
 
# execute_script 함수 사용 (자바스크립트로 아이디, 패스워드를 넘겨주는 형태)
driver.execute_script("document.getElementsByName('id')[0].value=\'"+id+"\'")
driver.execute_script("document.getElementsByName('pw')[0].value=\'"+pw+"\'")
 
driver.find_element_by_xpath('//*[@id="frmNIDLogin"]/fieldset/input').click()
 
time.sleep(2)
driver.close()
 
cs

사용된 document.getElementsByName('id')[0].value=\' 는 자바스크립트에서 사용되는 함수인데

파이썬에서 키를 직접적으로 넘겨주는 게 아니라 브라우져 내에서 자바스크립트로 아이디 값을 넘겨주기 때문에 네이버의 자동화된 소프트와 알고리즘을 우회하는 원리이다.

요즘 네이버는 자동로그인 같은 자동화된 소프트웨어를 막는 추세

execute_script도 언제든지 네이버의 조치에 의해 막힐 수 있다.

+ Recent posts