웹 스크래핑
웹에서 원하는 데이터를 추출하는 행위
웹 크롤링과의 차이
웹 스크래핑은 원하는 데이터만을 가져오는 것인 반면에 웹 크롤링은 웹페이지의 링크를 따라 모든 데이터를 가져오는 것임
<html>
<head> <!-- header 부분 -->
<meta charset="utf-8">
<title>test 홈페이지 입니다.</title> <!-- 홈페이지 타이틀 -->
</head>
<body> <!-- 본문 부분 -->
<input type="text", value="ID를 입력하세요"> <!-- type(세부 요소 종류)와 value(세부 요소의 값)는 attribute -->
<input type="password">
<input type="button" value="로그인">
<a href="http://www.google.com">구글로 이동하기</a>
</body>
</html>
<html></html> : html 파일 시작과 끝 부분 <head></head> : 웹 페이지의 header 부분<title></title> : 홈페이지의 제목 부분<meta> : html 파일의 메타 데이터를 지정 <body></body> : 웹 페이지의 본문 부분
https://www.w3schools.com/html/
- 최상위요소/상위요소/..../하위요소[index]/최하위요소
<index가 있는 경우에만 [index]로 지정>- {경로}[조건] <특정한 고유한 값이 존재할 때 사용>
요소
/ : 하위 단계// : 상위 단계* : element와 상관 없이 전체 검색@ : 속성예시 : id가 login인 모든 요소를 문서 전체에서 찾으시오
<place="elementary_school">
<grade value="1st">
<class value="1">
<student value="1">박명수</student>
<student value="2">유재석</student>
<student value="3">이정재</student>
<student value="4">이정재</student>
<student value="5">조세호</student>
</class>
<class value="2"></class>
<class value="3"></class>
</grade>
<grade value="2nd"></grade>
<grade value="3rd"></grade>
<grade value="4th"></grade>
<grade value="5th"></grade>
<grade value="6th"></grade>
</place>
pip install requests
import requests
res = requests.get("http://naver.com")
print("응답코드 :", res.status_code)
if res.status_code == requests.codes.ok:
print("정상입니다.")
else:
print(f"문제가 발생했습니다. [에러 코드 : {res.status_code}]")
res.raise_for_status()
print("웝 스크래핑을 진행합니다.")
res = requests.get("http://google.com")
res.raise_for_status()
print(res.text)
with open("mygoogle.html", "w", encoding="utf8") as file:
file.write(res.text)
도메인에서 해당 페이지 html파일을 가져옴 | 실행 결과 google 페이지와 같은 형태가 나타남 |
|---|
. : 하나의 문자 (ex: ca.e → care, cafe...)^ : 문자열의 시작 (ex: ^de → desk, destiny...)$ : 문자열의 끝 (ex: se$ → case, base...)import re
p = re.compile("ca.e")
def print_match(m):
if m:
print(m.group())
print(m.string)
print(m.start())
print(m.end())
print(m.span())
else:
print("매칭되지 않습니다.")
m = p.match("case")
print(m.group())
m = p.search("good care")
print_match(m)
lst = p.findall("good care cafe")
print(lst)

https://docs.python.org/ko/3.13/library/re.html
https://www.whatismybrowser.com/detect/what-is-my-user-agent/
request할 때 User Agent를 같이 보내 접근 권한 제한을 벗어날 수 있음
예시
import requests
url = "https://velog.io/@bdk0206/posts"
res = requests.get(url)
res.raise_for_status()
with open("velog.html", "w", encoding="utf8") as file:
file.write(res.text)
라는 코드가 있을 때 실행을 하면 오류가 발생하며 웹 페이지 정보가 누락되어 제대로 정보를 가져오지 못함
import requests
url = "https://velog.io/@bdk0206/posts"
headers = {"User-Agent": "Your-User-Agent"}
res = requests.get(url, headers=headers)
res.raise_for_status()
with open("velog.html", "w", encoding="utf8") as file:
file.write(res.text)
이 때, User Agent 정보를 request할 때 함께 보내주게 된다면 403 오류가 발생하지 않고 웹 페이지를 잘 가져오게 됨