[BS4] 인덱스를 기준으로 크롤링을 하는 방법

sonhm·2021년 4월 3일
post-thumbnail

인덱스를 기준으로 dict 반환

마크업 문서에서 크롤링할 어트리뷰트가 없는 경우, 인덱스를 이용하여 딕셔너리형식의 키와 값을 반환할 수 있다.

import os
import requests
from bs4 import BeautifulSoup

os.system('clear')
url = 'https://www.iban.com/currency-codes'
request = requests.get(url)

soup = BeautifulSoup(request.text, 'html.parser') #전체 마크업 문서 크롤링

countries = []
table = soup.find('table')
rows = soup.find_all('tr')[1:]

for row in rows:
  items = row.find_all('td') #1로우의 칼럼별로 리스트에 담는다.
  name = items[0].text #1번째 인자를 Name으로 반환
  code = items[2].text #3번째 인자를 Code로 반환
  if name and code:
    if name != 'No universal currency':
      country = {
        'name': name.capitalize(),
        'code': code
      }
      countries.append(country) #dict 형식으로 반환

print(countries)

find_all()

해당 soup 오브젝트들을 리스트 형태로 반환한다.

soup = BeautifulSoup(request.text, 'html.parser')
table = soup.find('table')
rows = soup.find_all('tr')

다음과 같은 조건으로 찾을 수 있다.
1. find_all(tag)
2. find_all(tag, value)
3. find_all(attr = value)

4. find_all(tag, {attr:value})

find_all()[n]

해당 리스트의 첫번째 soup 오브젝트를 반환한다.

soup = BeautifulSoup(request.text, 'html.parser')
table = soup.find('table')
rows = soup.find_all('tr')[0]

find()

해당 soup 오브젝트를 반환한다.





참고문서

마크업 문서
BS4 문서

profile
기발한 기발자

0개의 댓글