[기본 사용 방식 및 사용 예시]

1
2
3
4
5
6
# 현재 마우스 위치의 (x, y)좌표 반환
pyautogui.position() 
 
# 사용 예시
x, y = pyautogui.position()
print("x={0},y={1}".format(x,y)) 
cs

1
2
3
4
5
6
# 모니터 해상도 (가로, 세로) 반환
pyautogui.size()
 
# 사용 예시
width, height = pyautogui.size()  
print('width={0}, height={1}'.format(width, height)) 
cs

1
2
3
4
5
6
# 해당 좌표에 마우스 커서 시간 동안 이동
pyautogui.moveTo(x좌표, y좌표, 시간) 
 
# 사용 예시
pyautogui.moveTo(1001002)  
pyautogui.moveTo(2002002)
cs

1
2
# 안전모드 설정하기, 잘못되었을 경우 탈출구
pyautogui.FAILSAFE = True (False 값을 넣을 경우 오류 발생시 실행 멈추지 않음)
cs

1
2
3
4
5
# 상대좌표로 마우스 이동하기 ( 현재위치에서 참조값만큼 마우스 이동)
pyautogui.moveRel(x축 참조값, y축 참조값, 시간)
 
# 사용 예시
pyautogui.moveRel(None, 120,2)
cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 마우스 클릭하기
pyautogui.click()
 
# 마우스로 특정좌표 클릭하기
pyautogui.click(x=823, y=584)
 
# 마우스 오른쪽 클릭하기
pyautogui.click(button='right')
pyautogui.rightClick()  
 
# 마우스로 더블 클릭하기
pyautogui.click(clicks=2)
pyautogui.doubleClick()
 
# 시간 간격(인터벌)을 가지고 클릭하기
pyautogui.click(clicks=2, interval=1.5)  
 
# 마우스 버튼다운
pyautogui.mouseDown()
 
# 마우스 버튼업
pyautogui.mouseUp()  
cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 마우스 드래그 - 방법 1
pyautogui.mouseDown(x=261, y=12)
pyautogui.mouseUp(x=0, y=197)  
 
# 마우스 드래그 - 방법 2
# 마우스 현재 위치에서 x=100, y=100로 드래그
pyautogui.dragTo(x=100, y=100)
 
# 중간 지연 시간을 가지고 마우스 현재 위치에서 x=100, y=100로 드래그
pyautogui.dragTo(x=100, y=100, duration=2)  
 
# # 상대 좌표를 가지고 마우스 드래그
pyautogui.dragRel(-100-100, duration=2
 
cs

1
2
3
4
5
6
7
8
9
10
# 마우스 스크롤
 
# 위로
pyautogui.scroll(-100)
 
# 아래로
pyautogui.scroll(100)
 
# 특정 위치로 이동(x=100, y=100) 후 스크롤
pyautogui.scroll(100, x=100, y=100
cs

1
2
3
4
5
6
7
8
9
10
11
# 특정 문자열 입력하기
pyautogui.typewrite('Hello!')
 
# 특정 문자열 안정적으로 입력하기
time.sleep(1)  
pyautogui.typewrite('Hello!', interval=0.25)
 
# 한글 입력은 안 됨
pyautogui.typewrite('한글!'
#글을 적는 곳의 IME가 한글로 설정되어 있다면 영타로 쳐서 한글입력 가능
pyautogui.typewrite('gksrmf!'
cs

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# 엔터키 누르기
pyautogui.press('enter')
 
# 여러 키 연속으로 입력하기
pyautogui.press(['backspace''enter'])
 
# press 가능 키 리스트
['\t''\n''\r'' ''!''"''#''$''%''&'"'"'(',
')''*''+'',''-''.''/''0''1''2''3''4''5''6''7',
'8''9'':'';''<''=''>''?''@''[''\\'']''^''_''`',
'a''b''c''d''e','f''g''h''i''j''k''l''m''n''o',
'p''q''r''s''t''u''v''w''x''y''z''{''|''}''~',
'accept''add''alt''altleft''altright''apps''backspace',
'browserback''browserfavorites''browserforward''browserhome',
'browserrefresh''browsersearch''browserstop''capslock''clear',
'convert''ctrl''ctrlleft''ctrlright''decimal''del''delete',
'divide''down''end''enter''esc''escape''execute''f1''f10',
'f11''f12''f13''f14''f15''f16''f17''f18''f19''f2''f20',
'f21''f22''f23''f24''f3''f4''f5''f6''f7''f8''f9',
'final''fn''hanguel''hangul''hanja''help''home''insert''junja',
'kana''kanji''launchapp1''launchapp2''launchmail',
'launchmediaselect''left''modechange''multiply''nexttrack',
'nonconvert''num0''num1''num2''num3''num4''num5''num6',
'num7''num8''num9''numlock''pagedown''pageup''pause''pgdn',
'pgup''playpause''prevtrack''print''printscreen''prntscrn',
'prtsc''prtscr''return''right''scrolllock''select''separator',
'shift''shiftleft''shiftright''sleep''space''stop''subtract''tab',
'up''volumedown''volumemute''volumeup''win''winleft''winright''yen',
'command''option''optionleft''optionright']
 
# 조합 키 입력하기 (쉬프트 누르고 왼쪽으로 한 칸 선택한 후, 쉬프트 떼기)
pyautogui.keyDown('shift')  
pyautogui.press('left')  
pyautogui.keyUp('shift')  
 
# 복사 붙이기
# Ctrl + C (단축키 = hotkey)
pyautogui.hotkey('ctrl''c')
 
# Ctrl + V
pyautogui.hotkey('ctrl''v'
 
cs


[기본 사용 방식]


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import requests
from bs4 import BeautifulSoup as bs
 
url = 'https://news.naver.com/main/read.nhn?\
mode=LSD&mid=shm&sid1=101&oid=018&aid=0004305437'
= requests.get(url)
html = r.content 
 
soup = bs(html, "html.parser"
# request를 통해 파싱한 html문서를 BeautifulSoup 객체로 만들어 줌으로서
BeautifulSoup의 유용한 메서드(원하는 데이터 추출)를 사용하는 방식 
 
print('1. ', soup.title)
print('2. ', soup.title.name)
print('3. ', soup.title.string)
print('4. ', soup.title.parent.name)
print('5. ', soup.p)                 # 가장 첫 p 태그 반환
print('6. ', soup.p['class'])        # 원하는 태그의 속성에 대한 값을 파싱 가능
print('7. ', soup.a)
print('8. ', soup.find_all('a'))     # 모든 a태그 list값 반환
print('9. ', soup.find(id="right.ranking_tab_100"))  # id 값을 가지고 해당 태그 찾을 수 있음
print('10.', soup.get_text())        # text만 추출
cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
결과물
 
1.  <title>이재용 부회장, 새해 첫 출장 中시안 4일 출국..반도체 사업 점검 : 네이버 뉴스</title>
2.  title
3.  이재용 부회장, 새해 첫 출장 中시안 4일 출국..반도체 사업 점검 : 네이버 뉴스
4.  meta
5.  <p class="head_channel_layer" style="display: none;">
<span class="head_channel_layer_text">해당 언론사가 주요기사로<br/>직접 선정한 기사입니다.</span>
<a class="head_channel_layer_link" href="https://news.naver.com/main/static/channelPromotion.html" target="_blank">언론사 편집판 바로가기</a>
<button class="head_channel_layer_close" type="button">닫기</button>
</p>
6.  ['head_channel_layer']
7.  <a href="#lnb" tabindex="1"><span>메인 메뉴로 바로가기</span></a>
8.  [<a href="#lnb" tabindex="1"><span>메인 메뉴로 바로가기</span></a>, 
<a href="#main_content" tabindex="2"><span>본문으로 바로가기</span></a>, 
<a class="h_logo nclicks(STA.naver)" href="https://www.naver.com/"> ... 생략
9.  <a aria-selected="false" class="nclicks(rig.ranking)" href="#" id="right.ranking_tab_100" onclick="return false;">정치</a>
10. 이재용 부회장, 새해 첫 출장 中시안 4일 출국..반도체 사업 점검 : 네이버 뉴스... 생략
cs

[사용 예시]

ex.1) 뉴스 기사 html에서 a태그의 href 링크들만 크롤링하기



해당 뉴스기사 url에서 이 부분의 1번부터 10번까지의 링크를 크롤링하기


1
2
3
4
5
6
7
8
9
10
11
12
import requests
from bs4 import BeautifulSoup as bs
url = 'https://news.naver.com/main/read.nhn?\
mode=LSD&mid=shm&sid1=101&oid=018&aid=0004305437'
= requests.get(url)
html = r.content 
soup = bs(html, "html.parser"
a_tags = soup.find_all("a", {'class':"nclicks(rig.newstopic)"}) 
count = 1
for a_tag in a_tags :
    print(count,".", a_tag["href"] ) # 찾은 a태그의 href 값 크롤링
    count += 1
cs

1
2
3
4
5
6
7
8
9
10
11
결과값 확인
1 . https://search.naver.com/search.naver?where=nexearch&query=%EC%97%B0%ED%9C%B4+%EB%A7%88%EC%A7%80%EB%A7%89+%EB%82%A0&ie=utf8&sm=nws_htk.nws
2 . https://search.naver.com/search.naver?where=nexearch&query=2%EC%B0%A8+%EB%B6%81%EB%AF%B8%ED%9A%8C%EB%8B%B4&ie=utf8&sm=nws_htk.nws
3 . https://search.naver.com/search.naver?where=nexearch&query=%EC%8B%AC%EC%84%9D%ED%9D%AC+%EB%A9%94%EB%AA%A8&ie=utf8&sm=nws_htk.nws
4 . https://search.naver.com/search.naver?where=nexearch&query=%EC%9E%90%EC%A0%95%EC%AF%A4+%ED%95%B4%EC%86%8C&ie=utf8&sm=nws_htk.nws
5 . https://search.naver.com/search.naver?where=nexearch&query=12%EC%9D%BC+%EA%B2%80%EC%B0%B0+%EC%86%8C%ED%99%98%EC%A1%B0%EC%82%AC&ie=utf8&sm=nws_htk.nws
6 . https://search.naver.com/search.naver?where=nexearch&query=%EA%B5%AC%EC%A0%9C%EC%97%AD+%EB%B0%A9%EC%97%AD+%EC%B4%9D%EB%A0%A5&ie=utf8&sm=nws_htk.nws
7 . https://search.naver.com/search.naver?where=nexearch&query=%ED%95%9C%EA%B5%AD%EB%8B%B9+%EC%A0%84%EB%8B%B9%EB%8C%80%ED%9A%8C&ie=utf8&sm=nws_htk.nws
8 . https://search.naver.com/search.naver?where=nexearch&query=%ED%94%8C%EB%9D%BC%EC%8A%A4%ED%8B%B1+%ED%94%84%EB%A6%AC+%EC%B1%8C%EB%A6%B0%EC%A7%80+%EB%8F%99%EC%B0%B8&ie=utf8&sm=nws_htk.nws
9 . https://search.naver.com/search.naver?where=nexearch&query=%EB%B2%A0%ED%8A%B8%EB%82%A8%EC%84%9C+%EA%B0%9C%EC%B5%9C&ie=utf8&sm=nws_htk.nws
10 . https://search.naver.com/search.naver?where=nexearch&query=%EA%B5%AD%EC%99%B8+%EC%98%81%ED%96%A5%EC%9D%B4+75%25&ie=utf8&sm=nws_htk.nws
cs


[기본 사용 방식]


1
2
3
4
5
6
7
8
9
import requests
 
requests.get(...)            #get요청 (주로 html조회요청)
requests.post(...)           #post요청 (주로 추가/수정/삭제요청)
# get과 post의 차이 : 
# get은 데이터를 가져오는데 사용되고, 
# post는 서버의 데이터를 수정하는데 사용된다. 
requests.put(...)            #put요청
requests.delete(...)         #delete요청
cs


1
2
3
4
5
6
7
8
9
10
11
12
import requests
 
= requests.get(url 주소) #url주소에 데이터 요청
 
r.content                 # 응답 데이터(binary형식 내용,이미지파일 등) 
r.text                    # 응답 데이터(텍스트형식 내용, 텍스트 파일에 씀)
r.json                    # 응답 데이터 JSON형태
r.url                     # 해당 url 반환
r.status_code             # 응답 상태코드 (200 이면 성공)
r.headers                 # 응답 헤더의 {K:V} 형식의 딕셔너리 자료반환
r.encoding = 'utf-8'      # 응답 객체에 인코딩 지정
 
cs

[응답 상태코드 구분]

1xx : Informational (단순 정보 제공)

2xx : Successful (성공)

3xx : Redirect (추가 정보 필요)

4xx : Client error

5xx : Server error

특히, response 403 에러가 나는 경우 브라우저가 아닌 것(Python)에 대한 접속 차단으로 인한 것이다. 요청할 때, header에 User-Agent또는 Referer를 지정하고 접근하면 해결 가능하다.

[사용 예시]

ex.1) 요청시 headers에 User-Agent 정보를 크롬으로 지정하여 요청


1
2
3
4
5
6
7
8
9
10
11
12
13
import requests
 
# 요청시 헤더정보를 크롬으로 지정
request_headers = { 
'User-Agent' : ('Mozilla/5.0 (Windows NT 10.0;Win64; x64)\
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98\
Safari/537.36'), } 
 
url = "https://search.naver.com/search.naver"
response = requests.get(url,headers = request_headers)
 
print(response) 
#해당 url 요청할 때 headers를 임의로 설정하여 요청한 케이스
cs

ex.2) 요청시 headers에 Referer 정보를 바꾸어 웹에서 접속한 것으로 요청.

수요웹툰 페이지에서 접속한 것으로 요청하여, 웹툰 이미지 파일 가져오기


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import  os
import  requests
 
image_url = 'https://image-comic.pstatic.net/webtoon/626907/237\
/20190115192015_d9f2b6e9d878a372dfa6f07ebfc5f14a_IMAG01_1.jpg'
 
# Referer을 지정하여 수요웹툰 복학왕 페이지를 통해서 요청
headers = {'Referer''https://comic.naver.com/webtoon/list.nhn?\
titleId=626907&weekday=wed'}
 
response = requests.get(image_url, headers = headers)
print(response) # 접속 확인 (200 = 성공)
image_data = response.content           # binary형식
imgfile = os.path.basename(image_url)   # url을 이름으로 하는 비어있는 데이터생성
 
#파일에 이미지 데이터를 넣기
with open(imgfile, 'wb') as f:
    f.write(image_data)
cs



ex.3) 요청시 params지정을 활용한 뉴스기사 웹 크롤링

원하는 뉴스 기사를 들어가서 <F12>를 눌러 개발자 도구에 들어간 뒤, 다음과 같이 해당 페이지에 접속하기 위한 Parameters를 쉽게 추출할 수 있다.



이 Parameters는 다음과 같이 크롤링을 하고자 하는 url에서 "?"에 적혀있는 것 들이다.

https://news.naver.com/main/read.nhn?mode=LS2D&mid=shm&sid1=101&sid2=259&oid=009&aid=0004299807


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import requests
# 데이터를 요청하고자 하는 url = https://news.naver.com/main/read.nhn?\
# mode=LS2D&mid=shm&sid1=101&sid2=259&oid=009&aid=0004299807
# params를 지정하여 요청하는 것은 url뒤에 자동으로 ?와 &연산자로 묶어주는역할
 
url = "https://news.naver.com/main/read.nhn"
 
get_params = {
'mode''LS2D',
'mid''shm',
'sid1''101',
'sid2''259',
'oid''029',
'aid''0002506893'
}
 
= requests.get(url,params=get_params)
print(r.text) 
#해당 뉴스기사 데이터 가져오는 것 확인
cs




+ Recent posts