one step
[파이썬] webdrive 메서드와 url 매개변수가 다른 함수에 있을 때 본문
반응형
지시사항
함수 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()
반응형
'이것저것 코드 > 파이썬' 카테고리의 다른 글
[파이썬] 텍스트와 텍스트의 반복 수 조합해 딕셔너리 만들기 (0) | 2022.09.16 |
---|---|
[파이썬] 태그 수집, 중복 태그 수 세어 딕셔너리형으로 반환하기 (0) | 2022.09.16 |
[파이썬] 비동기 화면 크롤링하기 (wait 사용하기) (0) | 2022.09.16 |
[파이썬] 페이지네이션 있는 페이지에서 값 추출 및 딕셔너리 만들기 (1) | 2022.09.16 |
[파이썬] 국가명, 수도, 면적, 인구 추출해서 정리하기 (1) | 2022.09.16 |