파이썬(Python)

[Python] BeautifulSoup으로 HTML 파싱

zzoming 2023. 11. 7. 16:25

웹 페이지를 표현하는 HTML마크업 언어로 태그, 요소, 속성 등의 구성요소를 이용해 문서 구성을 구조적으로 표현하며, 구조화된 문서는 효율적으로 파싱(탐색)하고 원하는 정보를 찾아낼 수 있다. 

 

쉽게 말해서, HTML은 일정한 규칙에 따라 작성되기 때문에, 우리가 그러한 규칙만 잘 파악할 수 있다면 웹 상에서 원하는 데이터를 손쉽게 가져올 수 있다는 말이다. 

예를 들어보자
야구장에 수많은 관객들이 있다. 옆에 누군가가 멀리 보이는 관객들 중 한명을 집어서 저 사람한테 치킨을 가져다줘라고 하면 누구를 가리키는 것인지 쉽게 알 수 없다. 하지만 야구장의 객석은 구조화된 상태로 배열되어 있다. "A열 17번에 앉은 사람에게 치킨과 맥주를 가져다줘"와 같은 상태로 말할 수 있고, 우리는 누구를 지칭하는지 쉽게 이해할 수 있다. 

 

컴퓨터가 눈으로 HTML 문서를 보자마자 "아 이건 HTML 문서이고, 이러한 구조로 이루어져있꾸나"와 같이 한번에 이해하지 못한다. 그래서 우리는 컴퓨터에게 "이건 HTML 문서니까, HTML 문서에 맞게 구조화 해서 읽고 해석해라"라고 명령을 내려야 한다. 우리는 이 작업을 파싱(parsing) 이라고 하며, 파싱을 하는데 사용되는 라이브러리가 BeaurifulSoup이다. 

 

https://beautiful-soup-4.readthedocs.io/en/latest/

 

Beautiful Soup Documentation — Beautiful Soup 4.4.0 documentation

Non-pretty printing If you just want a string, with no fancy formatting, you can call unicode() or str() on a BeautifulSoup object, or a Tag within it: str(soup) # ' I linked to example.com ' unicode(soup.a) # u' I linked to example.com ' The str() functio

beautiful-soup-4.readthedocs.io


BeautifulSoup 라이브러리

: HTML , JSON , XML 와 같은 문서를 파싱하는데 주로 사용된다.

 

HTML 파일로 BeautifulSoup객체를 만들 수 있다. 변수이름은 관습적으로 Soup라고 짓는다 

"html.parser"의 의미는 BeautifulSoup객체에게 "HTML 문서에 맞게 구조화해서 읽고 해석해라" 라고 알려주는 것이다. 

 

file = annotation_list[0]
print(file) 

# 실행결과
/content/annotations/maksssksksss0.xml

with open(file) as f :
    data = f.read()
    soup = BeautifulSoup(data , 'html.parser')
	
# maksssksksss0.xml이라는 xml 파일로 BeautifulSoup 객체를 만들어줌

 

open() 함수는 파일에 대한 객체를 만드는 함수 

태그 추출하기 

find , find_all : HTML 태그를 추출하는 메소드 

  • find는 HTML 태그 한 개를 추출
  • find_all 은 HTML 태그를 여러개 담고 있는 리스트를 추출
print(soup.find('obejct'))

#실행결과 
<object>
<name>without_mask</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<occluded>0</occluded>
<difficult>0</difficult>
<bndbox>
<xmin>79</xmin>
<ymin>105</ymin>
<xmax>109</xmax>
<ymax>142</ymax>
</bndbox>
</object>

 

print(soup.find_all('object'))

#실행결과
[<object>
<name>without_mask</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<occluded>0</occluded>
<difficult>0</difficult>
<bndbox>
<xmin>79</xmin>
<ymin>105</ymin>
<xmax>109</xmax>
<ymax>142</ymax>
</bndbox>
</object>, <object>
<name>with_mask</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<occluded>0</occluded>
<difficult>0</difficult>
<bndbox>
<xmin>185</xmin>
<ymin>100</ymin>
<xmax>226</xmax>
<ymax>144</ymax>
</bndbox>
</object>, <object>
<name>without_mask</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<occluded>0</occluded>
<difficult>0</difficult>
<bndbox>
<xmin>325</xmin>
<ymin>90</ymin>
<xmax>360</xmax>
<ymax>141</ymax>
</bndbox>
</object>]

 

 

get_text() : BeautifulSoup객체에 get_text메소드를 적용하면 태그에서 딱 텍스트만 출력된다. 

 

위 xml파일에서 xmin , ymin , xmax , ymax 를 가져와보자

file = annotation_list[0]

with open(file) as f :
    data = f.read()
    soup = BeautifulSoup(data , 'html.parser')
    objects = soup.find_all('object')

    
    for object in objects :

        xmin = object.find('xmin').get_text() 
        ymin = object.find('ymin').get_text()
        xmax = object.find('xmax').get_text() 
        ymax = object.find('ymax').get_text()
        
        print([xmin, ymin, xmax ,ymax])
        
        
#실행결과 

['79', '105', '109', '142']
['185', '100', '226', '144']
['325', '90', '360', '141']

 


😯 BeuatifulSoup의 뜻

 

라이브러리 BeautifulSoup의 이름은 tage soup에서 유래한다. tag soup이란 문법,구조적으로 잘못된 HTML 웹 문서를 일컫는 말이다. HTML 문서는 오류에 유연하게 대응할 수 있기에 웹 개발자들이 엄격하게 규칙을 따르지 않은 경우가 많았는데 HTML과 텍스트가 마구잡이로 뒤섞이고 닫는 태그도 제대로 지켜지지 않을 때도 있었다. 

이렇게 dirty한 구조를 가진 웹문서를 두고 마구 뒤섞인 수프와 같다고 해서 tag soup란 이름이 붙었다. 

BeautifulSoup은 이러한 tag soup을 아름답게 변환시켜준다는 의미에서 지은 이름이다


📝참고자료 

https://celltong.tistory.com/entry/%ED%8C%8C%EC%9D%B4%EC%8D%AC-%ED%81%AC%EB%A1%A4%EB%A7%81

 

파이썬 크롤링 - BeautifulSoup 기본 개념

크롤링이란? : 웹 페이지에서 필요한 데이터를 추출해내는 작업. 크롤링을 하는 프로그램은 크롤러라고 함. BeautifulSoup 라이브러리 : HTML, XML, JSON 등 파일의 구문을 분석하는 모듈. 웹 페이지를 표

celltong.tistory.com

https://blog.naver.com/draco6/221928851789

 

크롤링 초급 강좌 6) BeautifulSoup

지난 시간 우리는 HTML의 기본 구조에 대해 살펴보았다. 기억나지 않는 분들을 위해 다시 한 번 요약해...

blog.naver.com