1

I am trying to switch into second iframe of the website for personal auto-filler for my business.

Just in case I might get marked as dup, I tried Python Selenium switch into an iframe within an iframe already and sadly got not much out of it.

Here are html codes for two iframes. Second iframe is within the first one:

<div id="tab2_1" class="cms_tab_content1" style="display: block;">
    <iframe id="the_iframe"src=
"http://www.scourt.go.kr/portal/information/events/search/search.jsp">
</iframe> <!-- allowfullscreen --></div>


<div id="contants">
<iframe frameborder="0" width="100%" height="1100" marginheight="0" 
marginwidth="0" scrolling="auto" title="나의 사건검색" 
src="http://safind.scourt.go.kr/sf/mysafind.jsp
sch_sa_gbn=&amp;sch_bub_nm=&amp;sa_year=&amp;sa_gubun=&amp;sa_serial=&amp;x=&amp;
y=&amp;saveCookie="></iframe>

<noframes title="나의사건검색(새창)">
<a href="http://safind.scourt.go.kr/sf/mysafind.jspsch_sa_gbn
=&amp;sch_bub_nm=&amp;sa_year=&amp;sa_gubun=&amp;sa_serial=&amp;x=&amp;y=&amp;
saveCookie=" target="_blank"
title="나의사건검색(새창)">프레임이 보이지 않을경우 이곳을 클릭해주세요</a></noframes></div>

Just for a reference- so far, I tried these:

#METHOD-1
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it(By.ID,"the_iframe"))
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it(By.CSS_SELECTOR,"#contants > iframe"))

#METHOD-2
driver.switch_to.frame(driver.find_element_by_xpath('//*[@id="the_iframe"]'))
driver.WAIT
driver.switch_to.frame(driver.find_element_by_css_selector('//*[@id="contants"]/iframe'))
driver.WAIT

#METHOD-3
iframe = driver.find_elements_by_tag_name('iframe')[0]
driver.switch_to.default_content()
driver.switch_to.frame(iframe)
driver.find_elements_by_tag_name('iframe')[0]

Here is the entire code I have right now:

import time
import requests
from bs4 import BeautifulSoup as SOUP
import lxml
import re
import pandas as pd
import numpy as np
from selenium import webdriver
from selenium.webdriver.support import ui
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support.ui import Select
import psycopg2

#ID and Password for autologin
usernameStr= 'personalinfo'
passwordStr= 'personalinfo'
driver = webdriver.Chrome('./chromedriver')
ultrawait = WebDriverWait(driver, 9999)
ConsumerName=""
COURTNO=""
CASENO=""
CaseYear=""
CaseBun=""
CaseSerial=""

#AutoLogin
driver.get("http://PERSONALINFO")
username = driver.find_element_by_name('userID')
username.send_keys(usernameStr)
userpassword = driver.find_element_by_name('userPassword')
userpassword.send_keys(passwordStr)
login_button=driver.find_elements_by_xpath("/html/body/div/div[2]/div/form/input")[0]
login_button.click()



#Triggered when str of URL includes words in look_for 
def condition(driver):
        look_for = ("SangDamPom", "jinHaengNo")
        url = driver.current_url
        WAIT = WebDriverWait(driver, 2)
        for s in look_for:
            if url.find(s) != -1:

                url = driver.current_url
                html = requests.get(url)
                soup = SOUP(html.text, 'html.parser')
                soup = str(soup)

                   #Some info crawled
                CN_first_index = soup.find('type="text" value="')
                CN_last_index = soup.find('"/></td>\n<t')
                ConsumerName=soup[CN_first_index+19:CN_last_index]
                ConsumerName.replace(" ","")

                   #Some info crawled
                CTN_first_index = soup.find('background-color:#f8f8f8;')
                CTN_last_index = soup.find('</td>\n<td height="24"')
                COURTNO = soup[CTN_first_index+30:CTN_last_index]
                COURTNO = COURTNO.replace('\t', '')

                    #Some info crawled
                CAN_first_index = soup.find('가능하게 할것(현제는 적용않됨)">')
                CAN_last_index = soup.find('</a></td>\n<td height="24"')
                CASENO=soup[CAN_first_index+19:CAN_last_index]
                CaseYear=CASENO[:4]
                CaseBun=CASENO[4:-5]
                CaseSerial=CASENO[-5:]

                print(ConsumerName, COURTNO, CaseYear, CaseBun, CaseSerial)

                #I need to press this button for iframe I need to appear.
                frame_button=driver.find_elements_by_xpath("//*[@id='aside']/fieldset/ul/li[2]")[0]
                frame_button.click()
                time.sleep(1)

            #Switch iframe
driver.switch_to.frame(driver.find_element_by_xpath('//*[@id="the_iframe"]'))
                        driver.wait
                        driver.switch_to.frame(driver.find_element_by_xpath("//iframe[contains(@src,'mysafind')]"))
                        time.sleep(1)
                        #Insert instit.Name
                        CTNselect =         Select(driver.find_element_by_css_selector('#sch_bub_nm'))
                        CTNselect.select_by_value(COURTNO)
                        #Insert Year
                        CYselect =         Select(driver.find_element_by_css_selector('#sel_sa_year'))
                        CYselect.select_by_value(CaseYear)
                        #Insert Number
                        CBselect =         Select(driver.find_element_by_css_selector('#sa_gubun'))
                        CBselect.select_by_visible_text(CaseBun)
                        #사건번호 입력 (숫자부분)
                        CS_Insert =         WAIT.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#sa_serial")))
                        CS_Insert.click()
                        CS_Insert.clear()
                        CS_Insert.send_keys(CaseSerial)
                        #Insert Name
                        CN_Insert =         WAIT.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#ds_nm")))
                        CN_Insert.click()
                        CN_Insert.clear()
                        CN_Insert.send_keys(ConsumerName)

                        break



ultrawait.until(condition)

Don't mind indention errors, problem of copy-paste.

I think its from #Switch iframe I have issue with.

Those inputs that come after #Switch iframe are all functional. I've tested them by opening iframe at another tab.

NulliPy
  • 133
  • 8
  • is there a public start url for this? – QHarr Feb 26 '19 at 17:01
  • It's private website as of now. Sorry I can't share that :( – NulliPy Feb 26 '19 at 17:20
  • @RatmirAsanov: your edits have been rolled back here. If you wish you can either discuss with the OP or flag for a moderator. – halfer Feb 26 '19 at 17:37
  • I literally mentioned "Possible duplicate" method in my original question. Do you just read title and mark dups? – NulliPy Feb 26 '19 at 19:25
  • @NulliPy Merely mentioning _just in case I might get marked as dup_ doesn't makes your question different from the existing ones. Perhaps _"Possible duplicate"_ is not a method. The question heading `Switching into second iframe in Selenium Python3` and the handcrafted _HTML_ have no link to your comment to the answers as _Sorry for the confusion; HTML is really far apart from one another, but the second one is really under the first one; code is just for reference_. – undetected Selenium Feb 26 '19 at 19:55
  • Oh sure. Lemme just open another question because that link got me nothing. – NulliPy Feb 26 '19 at 22:49

2 Answers2

1

You need to deal with your frames separately: When you finished working with one of them and want to switch to another -- you need to do:

driver.switch_to.default_content()

then switch to another one.

Better to use explicit wait for switching to the frame:

from selenium.webdriver.support import ui
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By


ui.WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, "#contants>iframe")))

wherein By you can use any locator.

Ratmir Asanov
  • 6,237
  • 5
  • 26
  • 40
  • Sorry for the confusion; HTML is really far apart from one another, but the second one is really under the first one; code is just for reference. – NulliPy Feb 26 '19 at 17:29
  • And I tried your method just now, it seems to work for the first iframe but not the second one, which I again clarify that it is under the first one. – NulliPy Feb 26 '19 at 17:31
  • @NulliPy, you are doing nothing inside the first frame. Why are you switching it? (I see that you are figured out your problem). Next time describe your question more clearly :) Thanks. – Ratmir Asanov Feb 26 '19 at 19:46
0

As per your html structure, both the iframes are different and the second one is not in between the first one. It would have been inside the first one if the html structure was like:

<div>
    <iframe1>
        <iframe2>
        </iframe2>
    </iframe1>
</div>

But as your first <div> and first <iframe> are ending before starting the second div and iframe, it means both the iframes are seperate.
So, according to your requirements, you just need to switch to the second iframe which can be done using:

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it(By.CSS_SELECTOR,"second iframe css"))

Updated Answer:
Try the code:

driver.switch_to.frame(driver.find_element_by_xpath('//*[@id="the_iframe"]'))
driver.WAIT
driver.switch_to.frame(driver.find_element_by_xpath('//iframe[contains(@src,'mysafind')]'))
driver.WAIT
Sameer Arora
  • 4,439
  • 3
  • 10
  • 20
  • Sorry for the confusion; HTML is really far apart from one another, but the second one is really under the first one; code is just for reference. – NulliPy Feb 26 '19 at 17:29
  • What is the error that you are getting when you are trying your code ? – Sameer Arora Feb 26 '19 at 17:34
  • So I have a [def] to crawl information from same page and fill empty fields within iframe whenever I enter URL with specific words. Without selecting correct iframe, [def] just attempts to repeat (as requirement for [def] is URL). However, I must mention that it seems like I am able to switch to first or second iframe because when [def] repeats itself, button on default frame cannot be reached- which I assume is because different iframe is selected. – NulliPy Feb 26 '19 at 17:45
  • Ok, i have updated my answer and added new xpath for the second iframe, please try that and let me know if that works. – Sameer Arora Feb 26 '19 at 17:48
  • Thanks a bunch. Lemme try real quick! – NulliPy Feb 26 '19 at 17:50
  • This is really frustrating. Why does it not work. Guh. I've been literally stuck with this issue for 3 hours... – NulliPy Feb 26 '19 at 18:02
  • What is the stacktrace that you are getting ? – Sameer Arora Feb 26 '19 at 18:03