6일차 python 크롤링

차지예·2025년 5월 20일

생성AI

목록 보기
6/56
post-thumbnail

오늘은 크롤링하는 방법을 배웠기때문에 코드가 많을 예정이다
velog에는 간단한 문법적인 이야기만 적을 것이고
자세한 코드는 깃허브에 정리할 예정이다.

🟡크롤링

필수 라이브러리

pip install requests
pip install beautifulsoup4
pip install selenium

BeautifulSoup 주요 문법 정리

기능문법 예시설명
특정 태그 찾기 (1개)soup.find('div')첫 번째 <div> 태그 찾기
특정 태그 모두 찾기 (여러 개)soup.find_all('a')모든 <a> 태그 리스트로 반환
클래스명으로 찾기soup.find('div', class_='header')class는 class_로 써야 함
id로 찾기soup.find(id='main-content')태그의 id 속성으로 찾기
속성(attribute) 추출tag['href']<a> 태그의 href 속성 가져오기
텍스트 추출tag.text.strip()태그 안의 순수 텍스트만 가져오기

requests 주요 문법

response = requests.get('https://example.com')
html = response.text       # HTML 내용
status = response.status_code  # HTTP 상태 코드 (200, 404 등)

Selenium 요소 찾기 방식

방식예시
태그 이름으로find_element(By.TAG_NAME, 'a')
클래스 이름으로find_element(By.CLASS_NAME, 'title')
id로find_element(By.ID, 'search-box')
name으로find_element(By.NAME, 'q')
XPath로find_element(By.XPATH, '//div[@class="title"]')
CSS 선택자find_element(By.CSS_SELECTOR, '.class > span')

0개의 댓글