Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
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
Archives
Today
Total
관리 메뉴

one step

[파이썬] webdrive 메서드와 url 매개변수가 다른 함수에 있을 때 본문

이것저것 코드/파이썬

[파이썬] webdrive 메서드와 url 매개변수가 다른 함수에 있을 때

원-스텝 2022. 9. 16. 18:03
반응형

도서 제목 수집

도서 구매 사이트를 크롤링해보도록 하겠습니다. http://books.toscrape.com/

 

지시사항

함수 crawl_contents가 올바르게 구현되어야 합니다.

crawl_contents 함수

  • 매개변수: webdriver와 스크래핑 해야 하는 웹 페이지의 url
  • 반환값: 페이지에 존재하는 도서 총 20권의 제목(문자열)을 담고 있는 list

(단, 도서의 제목이 말줄임표(...)로 생략되지 않은 형태로 출력되어야 합니다.)

main 함수

main 함수에서 crawl_contents 함수를 호출하여 구현 결과를 테스트해볼 수 있습니다.

채점 기준

crawl_contents 함수의 반환값이 올바른 값이라면 정답으로 처리됩니다.

Tips!

webdriver 는 main 함수에서 이미 실행된 것에 유의하여 crawl_contents 함수를 작성해주세요.

# 초기 코드
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.expected_conditions import presence_of_element_located
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.firefox.options import Options as FirefoxOptions


def crawl_contents(driver, url):

    titles = []

    # list를 반환합니다.
    return titles


def main():
    # 브라우저 web driver 설정(Firefox)
    options = FirefoxOptions()
    with webdriver.Firefox(options=options) as driver:

        # 데이터를 가져올 사이트의 URL
        url = "http://books.toscrape.com/catalogue/category/books/mystery_3/index.html"

        print(crawl_contents(driver, url))


if __name__ == "__main__":
    main()
# 완성 코드
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.expected_conditions import presence_of_element_located
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.firefox.options import Options as FirefoxOptions

    
def crawl_contents(driver, url):
    titles = []
    driver.get(url)
    
    image_container = driver.find_elements_by_class_name('image_container')
    for a in image_container:
        img = a.find_element_by_tag_name('img')
        title = img.get_attribute('alt')
        titles.append(title)

    # list를 반환합니다.
    return titles


def main():
    # 브라우저 web driver 설정(Firefox)
    options = FirefoxOptions()
    with webdriver.Firefox(options=options) as driver:

        # 데이터를 가져올 사이트의 URL
        url = "http://books.toscrape.com/catalogue/category/books/mystery_3/index.html"

        print(crawl_contents(driver, url))


if __name__ == "__main__":
    main()
반응형