크롤링 모듈
import requests
from bs4 import BeautifulSoup
print(dir(BeautifulSoup)) #모듈의 클래스 목록 출력함
변수=requests.get(): 원하는 소스코드를 가져오고
BeautifulSoup(변수.text, 'html.parser'): 태그를 확인하기 편해짐
*html.parser: html 문법 규칙에 따르는 문자열을, 해당 문법을 바탕으로 단어의 의미나 구조를 분석하는 parse를 행하는 프로그램을 일컬음.
soup.find('태그')
soup.find_all('태그')
find(): 가장 먼저 등장하는 해당 태그 값을 가져옴
find_all(): 해당 태그를 가진 모든 값을 리스트 형식으로 가져옴
*find()로 더 크게 감싸는 html 태그로 추출 후, 추출된 데이터에서 find_all()로 원하는 부분 추출
re.match(pattern, '문자열')
re.search(pattern, '문자열')
re.findall(pattern, '문자열')
match(): string의 맨 처음이 pattern과 일치하는지 확인함
search(): string에서 pattern과 일치하는 부분이 있는지 확인함
findall(): 일치하는 부분을 list로 반환함
# 정규표현식
import re
re.match(pattern, string)
print(re.search('world', 'hello world'))
re.search(pattern, string)
print(re.search('world', 'hello world hi world'))
None
<re.Match object; span=(6, 11), match='world'>
obj = re.search('world', 'hello world')
#<re.Match object; span(6, 11), match='world'>
obj.group() #'python'
obj.start() #6
obj.end() #12
obj.span() #(6, 11)
type(obj.span()) #<class 'tuple'>
'''
<html>
<body>
<ul>
<li>hello</li>
<li>welcome</li>
<li>bye</li>
</ul>
</body>
</html>
'''
A = soup.find('ul')
B = A.findAll('li')
print(B[2].text) #bye 출력
findAll(): 조건에 해당하는 모든 요소를 []로 추출함, 인덱싱 해서 n번째 값을 뽑을 수 있음
속성값에 id가 있으면 id = 'id값'
class가 있으면 class_='class값'
# 제목 가져오기
title = soup.find('태그', class_='클래스명')
title.get_text()
.get_text(): 태그에 들어있는 값(value)을 불러옴
.text: 태그 사이의 텍스트를 뽑음
# 작성날짜 가져오기
info = soup.find('span',class_='info_view')
print(info)
print(info.find('span',class_='num_date').get_text())
class가 num_date인데, info_view 안에 속해있음.
info_view 먼저 가져와 범위를 제한한 뒤 원하는 부분만 가져옴.
# 본문 가져오기
body = soup.fin('태그', id='id명')
body.find_all('p')
contents =''
for i in body.find_all('p'):
contents += i.get_text().strip()
contents
contents라는 빈 문자열을 만들어 반복문을 활용함.
strip(): 필요 없는 부분을 제거한 뒤 값을 반환함.
*문자 전처리 할 떄 strip(), split() 사용
# 문자열에서 숫자 추출
data = ''''fd34j5s9qvp1po'''
N_data = re.findall('[0-9]',data) #[\d]와 동일
A_data = re.findall('[^0-9]',data) #숫자를 제외한 모든 값, [\D]
T_data = re.findall('[a-z]',data) #a~z에 해당하는 값
print(type(N_data))
['3', '4', '5', '9', '1']
['f', 'd', 'j', 's', 'q', 'v', 'p', 'p', 'o']
<class 'list'>
blog.naver.com/schatz37/222157904118
[파이썬] 크롤링 : BeautifulSoup 모듈 사용하기 (find(), find_all() ~ 뉴스기사 제목,본문 추출하기)
패스트캠퍼스 강의를 참고하고 개인적으로 공부한 내용을 작성한 내용입니다.1. BeautifulSoup 모듈 Bea...
blog.naver.com
blog.naver.com/wearetheone0514/222158020860
웹 크롤링 입문
공부를 위한 노트입니다.혹시 글을 읽으시며 잘못된 부분을 발견하신다면 부담갖지 마시고피드백 부탁드립...
blog.naver.com
blog.naver.com/popqser2/221397907165
파이썬 - 정규 표현식을 이용하여 문자열 안에 숫자&문자 추출하기
0x00 개요데이터 분석 중 은근히 문자열 부분을 다룰 일이 많다. 간단하게는 불필요한 문자를 삭제할 때 메...
blog.naver.com
blog.naver.com/mmda23/222126283055
Python 정규표현식, import re
사실 몰라도 코딩테스트 문제를 풀 수 없는건 아니지만워낙 string 다루기가 편한 Python에서 정규표현...
blog.naver.com