[3주차] 파이썬 시작(beautifulsoup)

정우진·2022년 7월 17일
0

[주요내용]

  1. beautifulsoup 패키지는 크롤링을 할 때 특정 데이터를 쉽게 찾을 수 있도록 하는 기능을 가지고 있다

  2. 기본코드(requests 포함)
    import requests
    from bs4 import BeautifulSoup

    headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
    data = requests.get('https://movie.naver.com/movie/sdb/rank/rmovie.naver?sel=pnt&date=20210829',headers=headers)

    soup = BeautifulSoup(data.text, 'html.parser')

    print(soup)

    • data 부분의 url을 변경하여 사용
  3. 특정데이터를 찾을 때 코드

title = soup.select_one('검사에서 selector')
print(title.text) or print(title['href'])

  • soup.select_one 은 1개의 데이터를 찾음
  1. 여러개의 데이터를 찾을 때 코드
  • soup = BeautifulSoup(data.text, 'html.parser')

    #old_content > table > tbody > tr:nth-child(2) > td.title > div > a

    #old_content > table > tbody > tr:nth-child(4) > td.title > div > a

    movies = soup.select('#old_content > table > tbody > tr')

    for movie in movies:
    a = movie.select_one('td.title > div > a')
    if a is not None:
    print(a.text)

  • 2개 정도 검사에서 selector copy를 하여 붙여넣는다.

  • 공통으로 들어가는 코드는 movies로 묶어준다

  • 반복문을 통해 데이터 잘 나오는지 본다

  • 만약 데이터가 들어가 있지 않은 라인과 같은 tr이 존재하면 if 조건문을 통해서 is not None 또는 != None 으로 걸러주고 print를 한다

profile
야하마 군산악기사 운영자

0개의 댓글