Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- matplotlib
- 주피터노트북맷플롯립
- 파이썬수업
- sql연습
- python수업
- 주피터노트북그래프
- sql따라하기
- 팀플기록
- 판다스데이터분석
- sql연습하기
- SQL수업
- 파이썬차트
- 맷플롯립
- python데이터분석
- 주피터노트북판다스
- SQL
- 파이썬
- 파이썬데이터분석주피터노트북
- python알고리즘
- 파이썬데이터분석
- 판다스그래프
- 데이터분석시각화
- 주피터노트북
- 파이썬알고리즘
- SQLSCOTT
- 주피터노트북데이터분석
- 파이썬크롤링
- Python
- 수업기록
- 파이썬시각화
Archives
- Today
- Total
IT_developers
Python RPA(업무자동화) 개념 및 실습 - 크롤링(requests) 본문
RPA(Robotic Process Automation)
- 웹, 윈도우, 어플리케이션(엑셀 등)을 사전에 설정한 시나리오에 따라 자동적으로 작동하여 수작업을 최소화하는 일련의 프로세스
- RPA 사용 소프트웨어
- Uipath, BluePrism, Automation Anywhere, WinAutomation
- RPA 라이브러리
- pyautogui, pyperclip, selenium
크롤링 : 웹 사이트, 하이퍼링크, 데이터 정보 자원을 자동화된 방법으로 수집, 분류, 저장하는 것
URL 작업 - urllib 라이브러리 존재(파이썬)
- request
- urlretrieve()
- 요청하는 url의 정보를 파일로 저장
- 리턴값이 튜플 형태로 옴
- csv 파일, api 데이터 등 많은 양의 데이터를 한번에 저장
- urlopen()
- 다운로드 하지 않고 정보를 메모리에 올려서 분석
- read() : 메모리에 있는 정보를 읽어옴
- urlretrieve()
라이브러리 설치 : pip install requests
- requests
- urllib라이브러리 보다 간단한 방법으로 request 처리
- 디코딩도 알아서 해줌
- json 처리도 편함
- get(), post(),delete(),put() == REST 관련된 메소드 사용 가능
RPAbasic\crawl\requests1 폴더 - 1_request.py
import requests
# get 방식으로 처리
# 수신 데이터 == 응답 확인
print(res.text)
# 응답 상태
print(res.status_code) # 200
print(res.ok) # True
RPAbasic\crawl\requests1 폴더 - 2_method.py
메소드 연습 - 상용사이트로 이용할 수 없음.
# 연습용 사이트 이용
# url = "https://httpbin.org/" # A simple HTTP Request & Response Service.


import requests
# get 방식
# 파라메터 사용 - 주소줄에 같이 감
param = {"name": "hong"}
# parameter 없을 때 - res = requests.get(url)
res = requests.get(url, params=param)
print(res.headers)
print(res.text)

# post 방식 : 많은 내용의 data를 보내겠다. form 내용을 보냄.
data = {"name": "hong"}
res = requests.post(url, data=data)
print(res.text)
post 방식

delete 방식

# delete 방식
res = requests.delete(url)
print(res.text)

# put 방식 - form데이터 필요
data = {"name": "kim"}
res = requests.put(url, data=data)
print(res.text)

RPAbasic\crawl\requests1 폴더 - 3_json.py
json 처리
# 연습용 사이트 이용
# json 사이트 : https://jsonplaceholder.typicode.com/
import requests
res = requests.get(url)
print(res.text)
print(res.content) # binary 형식으로 가져올 때
print(res.json()) # json ==> dict
print(res.json().keys())
print(res.json().values())
# json 데이터 여러개 일 때 : 사이트에서 users 가지고 오기
res = requests.get(url)
for row in res.json():
for k, v in row.items():
print("key : {}, value : {}".format(k, v))
print()
# 10개의 데이터 값 출력


RPAbasic\crawl\requests1 폴더 - 4_headers.py
헤더 정보 가지고 오기
import requests
from fake_useragent import UserAgent
headers = {"user-agent": UserAgent().chrome}
res = requests.get(url, headers=headers)
print(res.text)
RPAbasic\crawl\requests1 폴더 - 실습_daum_kosdaq.py
urllib --> requests 변경
import requests
from fake_useragent import UserAgent
import csv
# 다음 주식 사이트
# 다운로드 기본경로
path = "./RPAbasic/crawl/download/"
# 빈 리스트 생성
data = []
try:
res = requests.get(url, headers=headers)
print(res.text)
rank_json = res.json()["data"]
for item in rank_json:
print(
"순위 {}, 금액 {}, 회사명 {}".format(
item["rank"], item["tradePrice"], item["name"]
)
)
data.append(item)
with open(path + "finanace.txt", "a", encoding="utf-8") as txt, open(
path + "finanace.csv", "a", encoding="utf-8", newline=""
) as csvfile:
# 텍스트 저장
txt.write(
"순위 {}, 금액 {}, 회사명 {}\n".format(
item["rank"], item["tradePrice"], item["name"]
)
)
# csv 저장
output = csv.writer(csvfile)
# 헤더명
output.writerow(data[0].keys())
for row in data:
output.writerow(row.values())
except Exception as e:
print(e)


RPAbasic\crawl\requests1 폴더 - 5_timeout.py
import requests
# url이 시간 안에 응답이 없다면 에러로 처리
res = requests.get(url, timeout=0.001)
print(res.text)
RPAbasic\crawl\requests1 폴더 - 6_exam.py
다음 쇼핑 베스트 100 리스트 가지고 오기
import requests
from fake_useragent import UserAgent
# F12 : Elements에 있는데 sources에 없으면 동적으로 내려온 데이터
# 100개의 데이터 가지고 오는 소스 찾기 ==> Fetch/XHR

# 순위, 제품명
res = requests.get(url)
# print(res.text) # 자료 확인
for idx, item in enumerate(res.json(), 1):
print(idx, item["product_name"])
'Python' 카테고리의 다른 글
Python RPA(업무자동화) 개념 및 실습 - 크롤링(Beautifulsoup)(2) (0) | 2022.09.28 |
---|---|
Python RPA(업무자동화) 개념 및 실습 - 크롤링(Beautifulsoup)(1) (0) | 2022.09.27 |
Python RPA(업무자동화) 개념 및 실습 - 크롤링(urllib) (1) | 2022.09.25 |
Python RPA(업무자동화) 개념 및 실습 - pyautogui (1) | 2022.09.24 |
Python RPA(업무자동화) 개념 및 실습 - 엑셀(3) (1) | 2022.09.23 |
Comments