Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Archives
Today
Total
관리 메뉴

RUBY

[WebData] 1. BeautifulSoup for web data 본문

데이터 분석/EDA_웹크롤링_파이썬프로그래밍

[WebData] 1. BeautifulSoup for web data

ruby-jieun 2023. 2. 5. 01:38

 

 

웹 데이터 수집하고 정리하기
1. BeautifulSoup for web data


 

 

BeautifulSoup

뷰티풀 수프(Beautiful Soup)는 HTML과 XML 문서들의 구문을 분석하기 위한 파이썬 패키지이다. HTML로부터 데이터를 추출하기 위해 사용할 수 있는 파싱된 페이지의 파스 트리를 만드는데, 이는 웹 스크래핑에 유용하다.
뷰티풀 수프는 이 프로젝트를 계속 기여하고 있는 Leonard Richardson이 시작하였다. 추가적인 지원은 오픈 소스 유지보수를 위한 유료 구독형인 Tidelift의 지원을 받는다.
파이썬 2.7과 파이썬 3용으로 사용 가능하다.

 

 

 

1. !pip install beautifulsoup4

!pip install beautifulsoup4

 

 

 

 

2.

  • 파일로 저장된 html 파일을 읽을 때
  • open : 파일명과 함께 읽기(r) / 쓰기(w) 속성을 지정
  • html.parser : Beautiful Soup의 html을 읽는 엔진 중 하나(lxml도 많이 사용)
  • prettify() : html 출력의 디자인을 넣어주는 기능

from bs4 import BeautifulSoup

page = open("../data/03. test_first.html", "r").read()
soup = BeautifulSoup(page, "html.parser")
print(soup.prettify())

 

 

 

2.

 - head 태그 확인 

soup.head

 

 - body 태그 확인

soup.body

 

 

3. 

 - p 태그 확인

 - 처음 발견한 p 태그만 출력

 - find()

soup.find("p")

 

 

 

4.

조건을 걸어 찾는다..

soup.find("p", class_="inner-text second-item")

 

soup.find("p", {"class":"outer-text first-item"}).text.strip()

 

다중 조건

soup.find("p", {"class":"inner-text first-item", "id":"first"})

 

 

 

 

5. 전부 찾자..

 - find_all(): 여러 개의 태그를 반환 

 - list 형태로 반환

soup.find_all("p")

 

 

 

6.

 - 특정 태그 확인하기

soup.find_all(id="pw-link")[0].text

 

 

 

 

7.

 - HTML 내에서 속성 id는 딱 한 번만 나타난다.

 - 그래서 find_all() 함수는 의미가 없다.

 - 단, 검색결과를 list로 받고 싶다면 id 라도 find_all() 함수를 사용한다.

soup.find(id="first")

 

 

 

8.

for each_tag in soup.find_all("p"):
    print("=" * 50)
    print(each_tag.text)

 

 

 

9. 외부로 연결되는 링크의 주소를 알아내는 방법

links = soup.find_all("a")
links[0].get("href"), links[1]["href"]
for each in links:
    href = each.get("href")
    text = each.get_text()
    print(text + "=>" + href)
Comments