• 목록
  • 아래로
  • 위로

안녕하세요?


새해의 첫 근무일 잘 보내고 계시는지요? ^^



어제 휴일이어서 예전에 작성한 Selenium을 이용하여 특정 element를 스크린 캡쳐하는 스크립트를 수정해봤는데요.


iframe 내의 element의 경우에 직접 접근할 수 없으므로 iframe_on = 1으로 대입한 경우에 switch_to.frame을 하도록 하도록 하였구요.


iframe_on = 0으로 대입한 경우에는 바로 element에 접근하도록 했는데요.



이렇게 일일이 iframe의 존재 여부 및 XPath값을 대입하지 않고서도 


원하는 element의 XPath만 입력받아서 iframe 내부에 존재하는 element에 접근할 수 있는 방법을 생각해보고 있는데 쉽지 않네요 ㅠㅠ


제가 뭔가 웹에 대한 이해가 전반적으로 부족한 것 같기도 하구요~


Selenium에서는 XPath를 이용하여 바로 접근할 수 있지만, BeautifulSoup에서는 이런 방식이 허용되지 않는 문제와 겹쳐서 더욱 어려운 것 같네요.


특정 XPath에서 parent 노드의 iframe을 알아내서 그 XPath값을 얻어낸다면 해결될 수 있는 문제 같은데요.


1. //*[@id="post_688075132"] // parent :: iframe 이런 방식으로는 접근이 안 되는 것 같네요. 다른 접근 방법은 없을까요??


2. BeautifulSoup에서 Xpath를 지원한다면 조금 수월하게 해결될지도 모르겠는데 그렇다면 lxml이나 htmlement를 사용하면 해결 가능할까요??

(설치해서 시도는 해봤는데 아직까지는 잘 안 되네요 ㅠㅠ)



그럼 주말에 다시 날씨가 쌀쌀해진다는데 감기 조심하시구요.


스포어 회원님들께 항상 감사드립니다!


좋은 오후 되세요~ ^^



from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
from PIL import Image
from io import BytesIO
import time

options = Options()
options.headless = True
driver = webdriver.Firefox(options=options)
driver.implicitly_wait(10)

url = 'https://cafe.naver.com/joonggonara/689072432' # iframe을 사용한 예제 페이지로 중고나라를 선택했습니다.
xpath_e = '//*[@id="post_689072432"]'
driver.get(url)
time.sleep(1)
WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.TAG_NAME, 'body')))

# 전체 페이지의 사이즈를 구하여 브라우저의 창 크기를 확대하고 스크린캡처를 합니다.
#driver.execute_script("document.body.style.zoom='zoom 100%'")
page_width = driver.execute_script('return document.body.parentNode.scrollWidth')
time.sleep(1)
page_height = driver.execute_script('return document.body.parentNode.scrollHeight')
time.sleep(1)
driver.set_window_size(page_width, page_height)
time.sleep(1)
png = driver.get_screenshot_as_png()
time.sleep(1)

# 특정 element 및 해당 iframe의 위치를 구합니다.

iframe_on = 1 # 만약 iframe이 없으면 0을 대입합니다.
if iframe_on == 1:
    #WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.XPATH, '//*[@id="cafe_main"]')))
    iframe = driver.find_element_by_xpath('//*[@id="cafe_main"]')
    iframe_location = iframe.location
    iframe_size = iframe.size
    driver.switch_to.frame(iframe)
    time.sleep(1)

element = driver.find_element_by_xpath(xpath_e)
image_location = element.location
image_size = element.size

# 이미지를 element의 위치에 맞춰서 crop 하고 저장합니다.
im = Image.open(BytesIO(png))

if iframe_on == 1:
    left = image_location['x'] + iframe_location['x']
    top = image_location['y'] + iframe_location['y']
    right = image_location['x'] + iframe_location['x'] + image_size['width']
    bottom = image_location['y']  + iframe_location['y'] + image_size['height']    
else:
    left = image_location['x']
    top = image_location['y']
    right = image_location['x'] + image_size['width']
    bottom = image_location['y'] + image_size['height']

im = im.crop((left, top, right, bottom))
rgb_im = im.convert('RGB')
filename = 'screenshot.jpg'
rgb_im.save(filename)
print('The element "' + xpath_e + '" was captured. : ' + filename)
driver.quit()



작성자
이니스프리 119 Lv. (1%) 3057190/115200000EXP

Make StudyForUs Great Again!

 

CSVpuymXAAAVVpd.jpg

댓글 2

포인트 폭탄+
이니스프리님 축하합니다.
추가로 200포인트만큼 포인트 폭탄+를 받았습니다.
comment menu
2020.01.02. 16:04

신고

"포인트 폭탄+님의 댓글"

이 댓글을 신고 하시겠습니까?

삭제

"포인트 폭탄+님의 댓글"

이 댓글을 삭제하시겠습니까?

이니스프리 작성자 → 포인트 폭탄+
profile image

포인트 폭탄+도 궁금했나 보네요 ^-^

comment menu
2020.01.02. 16:04

신고

"이니스프리님의 댓글"

이 댓글을 신고 하시겠습니까?

권한이 없습니다.
번호 제목 글쓴이 날짜 조회 수
공지 [1차 해결 및 추가] 서버 접속 불가 문제 안내 14 마스터 24.06.20.15:22 1027
공지 [작업 완료] 설 명절 맞이 서버 업데이트 안내 3 마스터 24.02.11.17:21 2999
공지 [중요] 호스팅 만료와 관련하여 일부 수칙이 변경됩니다. 4 마스터 23.01.14.02:23 6753
공지 [필독] 질문하는 방법 17 마스터 18.02.23.03:09 4737
286 핸드폰 유심이 이상해요. 7 슬기 20.06.01.19:18 227
285 Linux 시스템 보안에서 실무 등에서는 어떤 보안 솔류숀을 사용하는지 궁금해요 1 Seia 19.04.05.23:00 227
284 대구시 수돗물 발암물질 좀 도와주세요. 10 참비 18.06.22.10:55 227
283 인용문, 가로줄등이 작동하지 않습니다. 5 260578 17.12.03.17:44 227
282 DNS 관련 질문 (Netlify, CloudFlare) 5 밍원 22.02.14.15:24 226
281 흠.. 여기가 빠른 답변이 가능할까요? 3 워시퍼 19.02.26.15:21 226
280 호스팅신청페이지 및 FTP접속이 안됩니다. 4 image 막시모 18.12.20.10:56 226
279 호스팅 패널에서 웹사이트를 등록할 때 IPv4 주소가 *으로 나옵니다 4 하이빅스비 22.10.10.15:08 225
278 맥북 프로 구매와 관련하여 여쭤봅니다 4 image 이니스프리 20.01.20.13:03 225
277 판단 대기 시간 6 없음 19.01.11.14:09 225
276 홈서버용 CPU 좀 봐주시면 감사하겠습니다~ ㅠㅠ 7 image 이니스프리 20.02.24.22:40 224
275 제발 제 사이트링크 좀여 1 :셋탑_Setop 17.03.29.23:11 224
274 이미지가 align="center"을 사용해도 중앙정렬이 되지않습니다 4 image 손가락개 21.10.07.15:57 223
273 [앱개발 질문] 초보입니다. 2 Chobo 20.04.07.10:21 223
272 사이트 메인페이지에 갈림길 화면이 뜨게 하는 법에 대하여 어쭈어 봅니다. 5 image 입체그림 20.04.01.19:31 223
271 리눅스 오프라인 강좌의 수업 내용과 관련하여 질문 드립니다. 10 image 이니스프리 20.01.30.14:15 223
270 VPS에서의 Selenium 사용과 관련하여 질문 드립니다. 4 image 이니스프리 20.01.17.14:37 223
269 도메인 기관이전을 하려고 합니다 5 260578 19.06.13.22:18 223
268 제가 자바스크립트를 잘몰라서 원론적인 질문 하나 드립니다. 6 홀민 18.12.06.09:10 223
267 SQLite 2 Seia 17.12.03.11:24 223