DS School Week5-3 EDA:BeautifulSoup

Henny Song·2023년 6월 7일
0

DS Studylog

목록 보기
17/38
post-thumbnail

오늘 학습 계획

  • EDA 웹데이터 분석 강의 수강

학습 내용

1. EDA와 BeautifulSoup

  • BeautifulSoup이란?

    • (html) 태그로된 문서를 해석하는 기능을 가진 모듈
  • 불러오기
    from bs4 import BeautifulSoup

  • 파일 읽기

    • html 파일
      page = open('path/file', 'r').read()
      soup = BeautifulSoup(page, 'html.parser')

    • 웹 페이지
      from urllib.request import urlopen
      page =urlopen(url)
      soup = BeautifulSoup(page, 'html.parser')
      * html.parser : 엔진
      * page 대신 reponse, res도 사용함.

    • 웹페이지 2
      import requests
      response = requests.get(url)
      soup = BeautifulSoup(response.text, 'html.parser')

    • 웹페이지 3 : 한글이 주소인 경우
      import urllib
      from urllib.request import urlopen,Request
      # 한글 주소 변환
      html = 'url' + '{search_words}'
      fmt_words=urllib.parse.quote('korean_word')
      req = Request(html.format(search_words = fmt_words))
      #
      response = urlopen(req)
      soup = BeautifulSoup(response, 'html.parser')

    • 웹페이지 4 : 403 error 발생할 경우
      from urllib.request import Request, urlopen
      req = Request(url, headers={'user-agent':'Chrome'})
      response = urlopen(req)
      soup.BeautifulSOup(response, 'html.'arser')

    • 웹페이지 5 : 403 error 발생할 경우
      from urllib.request import Request, urlopen
      from fake_useragent import UserAgent
      ua = userAgent()
      req = Request(url, headers={'user-agent':ua.ie})
      response = urlopen(req)
      soup.BeautifulSOup(response, 'html.'arser')

    • 그 외
      print(soup.pretify()) : 들여쓰기 인식
      response.status : http 상태코드 반환

      import urllib.parse import urljoin
      urljoin(A, B) : 상대주소일 경우에만 url을 붙여서 절대 주소를 만들어 주는 함수

  • 찾기
    soup.tag : 특정 태그 1개 찾기
    soup.find('tag') : 특정 태그 1개 찾기
    soup.find('tag', class_= 'class_name' : 특정 클래스의 특정 태그 찾기
    soup.find(id = 'id name' : 특정 아이디 찾기
    soup.find('tag', {'class' : 'class_name', 'id':'id_name'} : 특정 조건의 특정 태그 찾기
    soup.select_one('tag') : 특정 태그로 찾기
    soup.select_one('.class') : 특정 클래스로 찾기
    soup.select_one('#id') : 특정 아이디로 찾기
    soup.select_one('.class > tag') : 특정 조건의 태그 찾기
    * '>' 은 바로 하위 항목을 지칭할때 쓴다.
    * 클래스에 띄어쓰기가 있을 경우 이중 클래스로서, 띄어쓰기 자리에 '.' 을 써준다.

    soup.find_all('tag'): 특정 태그 모두 찾기
    soup.find_alll('tag', 'class') : 특정 태그+클래스 모두 찾기
    soup.find_all(class_ = 'class_name') : 특정 클래스 모두 찾기
    soup.find_all(id = 'id name') : 특정 아이디 찾기 (리스트로 반환)

  • 텍스트값 찾기 * 태그로 싸여져 있는 텍스트 값
    tag.text.strip() :
    tag.get_text() : 태그로 싸여져 있는 텍스트값 불러오기
    tag.string

  • 속성값 찾기
    tag.['attribute']
    tag.get('attribute')

※ 기타 파이썬 함수

  • isinstance(data, type) : date가 type이 맞는지 확이하는 함수
  • re(regular expression) 모듈
    • re.split('a|b', string) : string을 a 혹은 b로 분리
    • re.search('search_word', string).group() : string에서 search_word값을 찾아서 반환해줌.
      * search_words 문법
      • '\a' : a가 필수
      • 'd' : 숫자
      • 'a+' : a가 1개 이상
      • 'a?' : a가 있을수도 있고 없을 수도 있음.
      • 'a|b' : a 또는 b
  • tqdm () : 반복문 진행 상황을 보여주는 함수
  • pd.date_range(date, periods=n, freq="D") : date에서부터 freq 간격의 날짜를 n일 생성해주는 함수
  • date.strftime('%Y-%m-%d') : date를 사용자 지정 형식으로 변경해 주는 함수
    * Y :4글자 년도, y : 2글자 년도
  • 'str{word}'.format(word="A") : 중괄호 안의 변수를 A로 변경해주는 함수
  • data.astype(type) : data를 새로운 type으로 형변환 시켜주는 함수
  • time.sleep(n) : n초후에 다음 실행문 실행

다음 학습 계획

  • EDA 유가분석 강의수강

0개의 댓글

관련 채용 정보