quilt code

[AI] BeautifulSoup 본문

daily/AI

[AI] BeautifulSoup

김뱅쇼 2023. 4. 25. 14:25

작성중

 


BeautifulSoup : 텍스트 형태의 html 데이터를 추출하기 위한 도구


설치) pip install beautifulsoup4

1. my_bs


<localhost:8000 데이터 를 beautifulsoup이용해서 text만 가져오기>


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
29
30
31
32
33
34
35
36
import requests
from bs4 import BeautifulSoup
 
url = 'http://localhost:8000/'
 
response = requests.get(url)
 
# #베낀 코드
# if response.status_code == 200:  #응답코드 200 : 서버가 성공했을때
#     html = response.text
#     soup = BeautifulSoup(html, 'html.parser')
#     title = soup.select('table > tr > td')
#
#     print(title[2].get_text() + " : " + title[3].get_text())
#     print(title[4].get_text() + " : " + title[5].get_text())
#
# else :  #에러코드 알려주는 것
#     print(response.status_code)
 
 
 
 
#강사님 코드   
html = response.text
soup = BeautifulSoup(html, 'html.parser')
trs = soup.find_all("tr")
for idx,i in enumerate(trs): 
    tds = i.find_all("td");
    if idx >0:
    
        print(tds[0].text,"    ",tds[1].text)
    
    
    
    
 
cs






url = 'http://localhost:8000/'      : 데이터를 받아오고자 하는 url

response = requests.get(url) : url

html = response.text   : html 정보 가져오기
---------------------여기까지 찍으면 



위와 같은 정보가 출력이 됨(print(html)
여기에서 tr과 td태그 안에 있는 정보만 가져와야함


soup = BeautifulSoup(html, 'html.parser')  : beautifulsoup 이용

trs = soup.find_all("tr")     : tr에 있는 정보를 가져와서 trs에 담겠다

for idx,i in enumerate(trs):    :for문을 이용해서 td안에 있는 정보 가져오기      
                                      
    tds = i.find_all("td");
    if idx >0:
    
        print(tds[0].text,"    ",tds[1].text)







* enumerate
: 리스트가 있는 경우 순서와 리스트의 값을 전달하는 기능(열거하다)
순서가 있는 자료형을 입력받아 인덱스 값을 포함하는 enumerate 객체 리턴

ex) items = [ "1", "2", "3"]
      for idx, i in enumerate(items):     : 여기에서 iitem 
           print("{} 과 {}".format(idx,i))

'daily > AI' 카테고리의 다른 글

[AI] YOLO  (0) 2023.06.16
[AI] 자동차 번호판 숫자 인식  (0) 2023.06.14
[AI] OpenCV  (0) 2023.04.22
[AI] tensorflow (3)  (0) 2023.04.22
[AI] cifar10  (0) 2023.04.20