inflearn logo
강의

Course

Instructor

Free Python Course (Usage Part 3) - Web Scraping (5 hours)

Quiz (Next Real Estate)

24년, 부동산 퀴즈 코드입니다. 참고하세요!!

177

hubhy4600

8 asked

0

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
from bs4 import BeautifulSoup

# Setup Chrome options
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
options.add_argument("--user-agent=''")

# Initialize the browser
browser = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)

# 옵션 추가 - 웹페이지 최대화
browser.maximize_window()

# 원하는 웹사이트로 이동 
url = "https://realty.daum.net/home/apt/danjis/38487"
browser.get(url)

# 모든 요소가 로드될 때까지 대기 (최대 10초)
WebDriverWait(browser, 10).until(EC.presence_of_all_elements_located((By.CLASS_NAME, "css-1dbjc4n")))

# 데이터 뽑기 시작
soup = BeautifulSoup(browser.page_source, "lxml")

# 매물 정보 가져오기
targets = soup.find_all("div", class_="css-1dbjc4n r-1awozwy r-s4x47v r-18u37iz r-17s6mgv r-1m04atk")

for idx, target in enumerate(targets):
    # 가격과 거래 방법 추출
    price = target.find("div", class_="css-1563yu1 r-aw03qq r-1wbh5a2 r-1w6e6rj r-159m18f r-1b43r93 r-b88u0q r-rjixqe r-13hce6t r-1ff274t r-13wfysu r-q42fyq r-1ad0z5i")
    if price:
        plate = price.get_text().split(" ")
        use = plate[0]

        final_price = ''
        for index in range(1, len(plate)):
            final_price += plate[index]
    else: 
        continue
    
    # 면적과 층수 정보 추출
    area_and_floors = target.find_all("div", class_="css-1563yu1 r-1dnsj32 r-1wbh5a2 r-1w6e6rj r-159m18f r-n6v787 r-majxgm r-14yzgew r-fdjqy7 r-13wfysu r-q42fyq r-1ad0z5i")
    if len(area_and_floors) >= 2:
        area = area_and_floors[0].get_text()
        floor = area_and_floors[1].get_text()[-3:]
    else:
        area = "N/A"
        floor = "N/A"

    print("=" * 10 + " 매물 {0} ".format(idx) + "=" * 10)
    print(f"거래 : {use}")
    print(f"가격 : {final_price}".strip())
    print(f"면적 : {area}".strip())
    print(f"층 : {floor}".strip())
    print()

browser.quit()

python 웹-크롤링 selenium 웹-스크래핑

Answer 1

0

communityai8509

안녕하세요, 인프런 AI 인턴입니다.

님의 코드는 Python을 사용하여 특정 부동산 웹사이트에서 매물 정보(거래 유형, 가격, 면적, 층수)를 스크래핑하는 예시입니다. Selenium과 BeautifulSoup라이브러리를 사용하여 웹 브라우저를 자동화하고 HTML에서 데이터를 추출합니다. 보여주신 코드는 아래와 같은 과정을 거칩니다:

  1. Selenium을 이용해 Chrome 웹드라이버를 초기화하고, 추가 옵션을 설정합니다.
  2. 원하는 부동산 웹페이지로 이동합니다.
  3. 해당 페이지의 모든 요소가 로드될 때까지 최대 10초간 기다립니다.
  4. BeautifulSoup를 이용해 현재 페이지의 소스를 파싱합니다.
  5. 원하는 매물 정보를 포함하고 있는 HTML 요소를 찾고, 그 안에서 거래 유형, 가격, 면적, 층수를 추출합니다.
  6. 추출한 정보를 출력합니다.

이 코드는 웹 스크래핑을 통해 특정 데이터를 수집하는 방법을 보여주며, 특히 웹 자동화 및 데이터 파싱에 있어서 매우 유용합니다. 경험을 쌓는데 도움이 될 것입니다.

selenium 업그레이드됨... 문법도 바뀜

1

286

1

2024.08.28 수요일 기준 날씨 정보 가져오기 소스코드입니다 (참고하세요 : ) )

0

230

1

git hub에 push할때 user-agent가 노출되도 상관이 없나요 ?

0

185

1

selenium 관련 web push notification 제어 질문

0

569

1

print(soup.a) 태그 값이 None으로 나옵니다.

0

1177

4

soup으로 검색한 버튼 또는 text를 click할때 어떻게 하나요 ?

1

3561

1

웹툰 사이트 body 안에가 안불러져옵니다.

0

677

2

네이버 웹툰을 활용한 BeautifulSoup 강좌에서 인터페이스가 달라졌습나다.

0

993

1

구글 무비 강좌에서요

0

399

0

네이버 IT뉴스 화면 requets.get 에러가 발생합니다ㅜ

0

432

0

23년 2월 7일, 다음 부동산 화면이 다름

0

404

0

네이버 항공권 관련 제가 작성한 코드 조심스럽게 공유해드립니다.ㅜ

7

2525

2

bs4 활용 2-1 질문합니다.

0

505

2

csv파일 깨짐

0

313

0

url 에러? (\UXXXXXXXX escape)

0

310

0

네이버 쇼핑으로 하면 왜 결과가 안 뜰까요?

0

380

0

쿠팡대신 네이버 쇼핑에서하는데, 5개 아이템만 나옵니다.

0

366

0

쿠팡 requests에 오류가 생기네요

0

2905

1

URL 문제

0

389

0

request 설치

0

315

0

from selenium import webdriver ?

0

348

1

네이버웹툰 랭크가 안불러져요...;;

0

299

0

안녕하세요 에러문의드려요

0

216

0

안녕하세요 오류해결부탁드립니다

0

336

0