在 Selenium Python3 中切换到第二个 iframe [英] Switching into second iframe in Selenium Python3

查看:50
本文介绍了在 Selenium Python3 中切换到第二个 iframe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试切换到网站的第二个 iframe,以便为我的业务进行个人自动填充.

为了防止我被标记为 dup,我尝试了 Python Selenium 已经切换到 iframe 内的 iframe,遗憾的是它没有得到太多.

这里是两个 iframe 的 html 代码.第二个 iframe 位于第一个内:

<iframe id="the_iframe"src=http://www.scort.go.kr/portal/information/events/search/search.jsp"></iframe><!-- 允许全屏 --></div><div id="contants"><iframe frameborder="0" width="100%" height="1100" marginheight="0"marginwidth="0" scrolling="auto" title="나의 사건검색"src="http://safind.scort.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="></iframe><noframes title="나의사건검색(새창)"><a href="http://safind.scort.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="目标="_blank"title="나의사건검색(새창)">프레임이 보이지 않을경우 이곳을클릭해주세요</a>

仅供参考 - 到目前为止,我尝试了这些:

#METHOD-1WebDriverWait(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-2driver.switch_to.frame(driver.find_element_by_xpath('//*[@id="the_iframe"]'))驱动程序等待driver.switch_to.frame(driver.find_element_by_css_selector('/​​/*[@id="contants"]/iframe'))驱动程序等待#METHOD-3iframe = 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]

这是我现在拥有的完整代码:

导入时间进口请求从 bs4 导入 BeautifulSoup 作为 SOUP导入 lxml进口重新将熊猫导入为 pd将 numpy 导入为 np从硒导入网络驱动程序从 selenium.webdriver.support 导入 ui从 selenium.webdriver.support 导入 expected_conditions 作为 EC从 selenium.webdriver.chrome.options 导入选项from selenium.webdriver.common.by import By从 selenium.webdriver.remote.webelement 导入 WebElement从 selenium.webdriver.support.ui 导入选择导入 psycopg2#ID 和密码用于自动登录usernameStr = '个人信息'passwordStr = '个人信息'driver = webdriver.Chrome('./chromedriver')Ultrawait = WebDriverWait(驱动程序,9999)消费者名称=""考特诺=""案例="案例年=""CaseBun=""CaseSerial=""#自动登录driver.get("http://PERSONALINFO")用户名 = 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()#当url的str包含look_for中的单词时触发定义条件(驱动程序):look_for = ("SangDamPom", "jinHaengNo")url = driver.current_urlWAIT = WebDriverWait(driver, 2)在look_for中为s:如果 url.find(s) != -1:url = driver.current_urlhtml = requests.get(url)汤 = SOUP(html.text, 'html.parser')汤 = str(汤)#抓取了一些信息CN_first_index = soup.find('type="text" value="')CN_last_index = soup.find('"/></td>\n<t')消费者名称=汤[CN_first_index+19:CN_last_index]ConsumerName.replace(" ","")#抓取了一些信息CTN_first_index = soup.find('背景色:#f8f8f8;')CTN_last_index = soup.find('</td>\n<td height="24"')COURTNO = 汤[CTN_first_index+30:CTN_last_index]COURTNO = COURTNO.replace('\t', '')#抓取了一些信息CAN_first_index = soup.find('사능하게할것(현제는적용않됨)">')CAN_last_index = soup.find('</a></td>\n<td height="24"')CASENO=汤[CAN_first_index+19:CAN_last_index]CaseYear=CASENO[:4]CaseBun=CASENO[4:-5]CaseSerial=CASENO[-5:]打印(消费者名称,COURTNO,CaseYear,CaseBun,CaseSerial)#我需要按下这个按钮才能显示我需要出现的 iframe.frame_button=driver.find_elements_by_xpath("///*[@id='aside']/fieldset/ul/li[2]")[0]frame_button.click()时间.睡眠(1)#切换iframedriver.switch_to.frame(driver.find_element_by_xpath('//*[@id="the_iframe"]'))驱动程序等待driver.switch_to.frame(driver.find_element_by_xpath("//iframe[contains(@src,'mysafind')]"))时间.睡眠(1)#插入 instit.NameCTNselect = Select(driver.find_element_by_css_selector('#sch_bub_nm'))CTNselect.select_by_value(COURTNO)#插入年份CYselect = Select(driver.find_element_by_css_selector('#sel_sa_year'))CYselect.select_by_value(CaseYear)#插入号码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)#插入名称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)休息超等待.直到(条件)

不要介意缩进错误、复制粘贴问题.

我认为它来自 #Switch iframe 我有问题.

#Switch iframe 之后的那些输入都是有效的.我已经通过在另一个标签页中打开 iframe 来测试它们.

解决方案

你需要单独处理你的框架:当您完成其中一个工作并想切换到另一个时-您需要执行以下操作:

driver.switch_to.default_content()

然后切换到另一个.

最好使用显式等待切换到帧:

from selenium.webdriver.support import ui从 selenium.webdriver.support 导入 expected_conditions 作为 ECfrom selenium.webdriver.common.by import Byui.WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, "#contants> iframe")))

其中 By 可以使用任何定位器.

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.

解决方案

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.

这篇关于在 Selenium Python3 中切换到第二个 iframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆