파이썬으로 웹 크롤링하기 (BeautifulSoup 사용)

2021. 1. 27. 02:26·Python
반응형

python에서 웹 크롤링하기 위해 모듈을 먼저 설치해주자.

-> pip install requests

이미 설치를 마쳤기에 already

import requests
res = requests.get("http://google.com")
print(res)

google을 접속해 정보를 가져온 후 res변수에 담아봤다.

실행화면

여기서 Reasponse 값이 200으로 나오는데 여기서 200은 정상으로 응답했다는 것이다.

 

import requests
res = requests.get("https://20s-hoon.tistory.com/")

with open("hoon.html", "w", encoding="utf8") as f:
    f.write(res.text)

내 블로그를 접속한후 hoon.html 파일로 내 블로그를 긁어와봤다.

위와 같이 잘 불러온 것을 볼 수 있다.

 

이제 beatifulsoup을 이용하여 필요한 정보를 가져오도록 하겠다.

먼저 설치부터 해주자

 

soup을 이용하여 정보를 가져오겠다.

20's의 정보는 <h1>태그안에 들어가 있는것을 볼 수있다.

여기서 soup.find라는 함수를 써서 20's를 가져와보겠다.

import requests
from bs4 import BeautifulSoup

res = requests.get("https://20s-hoon.tistory.com/")
soup = BeautifulSoup(res.text, "lxml")

print(soup.find("h1"))

같은 방식으로 태그, 속성값을 붙여서 좀더 정확하게 정보를 뽑아 올 수 있다.

분류 전체보기 밑 sorting algorithm을 뽑아오겠다

import requests
from bs4 import BeautifulSoup

res = requests.get("https://20s-hoon.tistory.com/")
soup = BeautifulSoup(res.text, "lxml")

print(soup.find("a", attrs={"class":"link_item"}))

블로그에는 뽑아올게 적어서 melon사이트를 이용하겠다.

멜론차트의 저 밤하늘의 별을 가져와보겠다.

li태그 클래스가 rank_item인 것을 가져오면 될 것 같다.

import requests
from bs4 import BeautifulSoup

url="https://www.melon.com/"
headers = {"User-Agent" :"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"}
res = requests.get(url, headers = headers)
soup = BeautifulSoup(res.text, "lxml")


print(soup.find("li",attrs={"class":"rank_item"}))
chart = soup.find("li",attrs={"class":"rank_item"})
print(chart.get_text())

멜론은 user-agent가 필요해 헤더에 user-agent정보를 추가해줬다.

차트의 밤하늘의 별을 밑부분 vss를 가져올려면 next_sibling을 쓰면된다. 아래코드의 next_sibling을 두번써준 이유는 한번만 썻을때 아무 출력값이 나오지 않았기때문에 개행이 있다 생각되어서 한번더 써줬다.

import requests
from bs4 import BeautifulSoup

url="https://www.melon.com/"
headers = {"User-Agent" :"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"}
res = requests.get(url, headers = headers)
soup = BeautifulSoup(res.text, "lxml")

chart = soup.find("li",attrs={"class":"rank_item"})
print(chart.next_sibling.next_sibling.get_text())
print(chart.next_sibling.next_sibling.next_sibling.next_sibling.get_text())

여기서 전체 값을 보고 싶으면 parent도 가능하다. (생략)

또한 원하는 텍스트의 태그정보를 가져 올 수도 있다.

import requests
from bs4 import BeautifulSoup

url="https://www.melon.com/"
headers = {"User-Agent" :"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"}
res = requests.get(url, headers = headers)
soup = BeautifulSoup(res.text, "lxml")
print(soup.find("a", text="밤하늘의 별을(2020)"))

 

멜론 최신음악 정보들을 다 가져와보자

div태그 클래스는 ellipsis rank01인 것들을 다 가져오면 될것같다.

여기서  a태그 href도 가져와보겠다.

import requests
from bs4 import BeautifulSoup

url="https://www.melon.com/new/index.htm"
headers = {"User-Agent" :"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"}
res = requests.get(url, headers = headers)
soup = BeautifulSoup(res.text, "lxml")

charts = soup.find_all("div", attrs={"class":"ellipsis rank01"})
for chart in charts:
    print(chart.get_text())
    print(chart.a["href"])

a태그 안에 링크가 걸려있으면 바로 이동가능한데 자바스크립트로 짜여져 있어서 멜론자체적으로 제공하는 음악재생 프로그램인듯 하다.

 

bs4를 이용하여 크롤링할때는 soup만 잘 써서 원하는 값을 가져오면된다.

반응형

'Python' 카테고리의 다른 글

파이썬을 이용하여 네이버 실시간 급상승검색어 가져오기  (0) 2021.01.27
파이썬으로 웹 크롤링하기 (Selenium 이용)  (0) 2021.01.27
Blind SQL Injection code form  (0) 2021.01.26
파이썬 정규식 (RegEx)  (0) 2021.01.17
enumerate와 list comprehension  (0) 2021.01.12
'Python' 카테고리의 다른 글
  • 파이썬을 이용하여 네이버 실시간 급상승검색어 가져오기
  • 파이썬으로 웹 크롤링하기 (Selenium 이용)
  • Blind SQL Injection code form
  • 파이썬 정규식 (RegEx)
Penguin Dev
Penguin Dev
What does the Penguin say?
    글쓰기 관리
  • Penguin Dev
    Pengha!
    Penguin Dev
  • 전체
    오늘
    어제
    • 분류 전체보기 (152)
      • Java & Spring (5)
      • System Hacking (4)
      • Algorithm (8)
        • Sorting algorithm (3)
      • Python (6)
      • Web (2)
        • Web Hacking & Security (2)
      • Write-Up (108)
        • pwnable.kr (17)
        • HackCTF (16)
        • 해커스쿨 FTZ (21)
        • LOB(lord of bufferoverflow) (19)
        • LOS (lord of sql injection) (28)
        • XSS-game (6)
        • Webhacking.kr (1)
      • SUA (19)
        • 오픈소스 보안 (19)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    computeifabsent
    LOB
    enumerate #list comprehension
    Java
    ConcurrentHashMap
    CountDownLatch
    spring
    ReentrantLock
    computeifabsent()
    spring boot
    쿠폰발급
    동시성
    AQS
    동시성처리
    tabat
    DB정리
    코드트리조별과제
    sqlinjection
    putval()
    hashmap vs concurrenthashmap
    코드트리
    thread-safe
    concurrenthashmap vs hashmap
    lord of bufferoverflow
    nop sled
    computeifpresent
    SpringBoot
    Lock
    computeifpresent()
    reentrantlock실습
  • 최근 댓글

  • 반응형
  • hELLO· Designed By정상우.v4.10.3
Penguin Dev
파이썬으로 웹 크롤링하기 (BeautifulSoup 사용)
상단으로

티스토리툴바