We provide programming data of 20 most popular languages, hope to help you!
Selenium can't found valid item from iframe. Ask Question Asked 1 month ago. and that code don't click at the item with id checkbox (check screenshot) i think the iframe upper makes big problems (check screenshot) if this is right version of solving problem, how to refocus Selenium onto that iframe? python selenium captcha hcaptcha. Share
self.driver.execute_script(f'document.getElementsByName("h-captcha-response")[0].setAttribute("h-captcha-response", "{token}")')
self.driver.execute_script(f'document.getElementsByName("g-recaptcha-response")[0].setAttribute("g-recaptcha-response", "{token}")')
self.driver.find_element_by_id('checkbox').click()
time.sleep(5)
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[starts-with(@name,'a-')]")));
@lcta0717 but you've mentioned that you can access an object HTMLIFrameElement, so you got the iFrame Element returned from web apis, as the link I've added details.The problem, possibly, is related to your xpath expression. Try running driver.find_elements_by_tag_name("iframe"), but please pay attention on the elements, in …
<html>
<body>
<div class="parent">
<iframe style="display: none"> ... </iframe>
<iframe style="display: none"> ... </iframe>
<iframe style="display: block">
#document
...
<div class="someClass"> ... </div>
</iframe>
<iframe style="display: none"> ... </iframe>
<iframe style="display: none"> ... </iframe>
</div>
</body>
Traceback (most recent call last):
File "myfile.py", line 60, in <module>
iframe = driver.find_element_by_xpath("//iframe[contains(@style, 'display: block')]")
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
return self.find_element(by=By.XPATH, value=xpath)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
'value': value})['value']
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: The result of the xpath expression "//iframe[contains(@style, 'display: block')]" is: [object HTMLIFrameElement]. It should be an element.
(Session info: chrome=93.0.4577.63)
iframes = driver.find_elements_by_xpath(".//iframe[contains(@style,'display: block')]")
parent = driver.find_element_by_xpath("//div[@class='parent']")
iframes = parent.find_elements_by_tag_name("iframe")
// when I print typeof iframes here, it's a list of dicts
// find the right index. Here, for simplicity, I just set it a default value
index = 4
// ...
driver.switch_to.frame(iframes[index])
Traceback (most recent call last):
File "myfile.py", line 76, in <module>
driver.switch_to.frame(iframe)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\switch_to.py", line 89, in frame
self._driver.execute(Command.SWITCH_TO_FRAME, {'id': frame_reference})
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: missing 'ELEMENT'
(Session info: chrome=93.0.4577.82)
[{}, {}, {}, {}, {u'ontouchmove': {}, u'ontouchstart': {}}, {}, {}, {}, {}, {}]
# switching to second iframe based on index
iframe = driver.find_elements_by_tag_name('iframe')[1]
# switch to selected iframe
driver.switch_to.frame(iframe)
try:
# instead of xpath = '//iframe' try accessing the parent element and add /iframe
iframe_xpath = '//*[@id="parent-element"]/iframe'
# or more specifically to get the right one in your case
iframe_xpath = '//*[@id="parent-element"]/iframe[contains(@style, "display: block")]'
WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.XPATH, iframe_xpath)))
driver.switch_to.frame(driver.find_element(By.XPATH, iframe_xpath))
# Do your thing in the frame
...
# go back to the normal content
driver.switch_to.default_content()
except:
# Ideally you catch each error separately; TimeoutException, NoSuchElementException, ...
pass
iframes = driver.find_elements_by_tag_name('iframe')
for iframe in iframes:
if 'block' in iframe.get_attribute('style'):
driver.switch_to.frame(iframe)
break
Example of Switching to iframe through ID: Let’s take an example to switch frame in Selenium displayed in the below image. Our requirement is to click the iframe. Nested iFrames in Selenium WebDriver. The Html code for the above nested frame is as shown below. The above HTML code clearly explains the iframe tag (highlighted in green
Int size = driver.findElements(By.tagName("iframe")).size();
WebDriver driver = new FirefoxDriver();
driver.get("http://demo.guru99.com/test/guru99home/");
driver.manage().window().maximize();
driver.switchTo().frame("a077aa5e");
driver.findElement(By.xpath("html/body/a/img")).click();
public class SwitchToFrame_ID {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver(); //navigates to the Browser
driver.get("http://demo.guru99.com/test/guru99home/");
// navigates to the page consisting an iframe
driver.manage().window().maximize();
driver.switchTo().frame("a077aa5e"); //switching the frame by ID
System.out.println("********We are switch to the iframe*******");
driver.findElement(By.xpath("html/body/a/img")).click();
//Clicks the iframe
System.out.println("*********We are done***************");
}
}
driver.switchTo().parentFrame();
driver.switchTo().defaultContent();
WebDriver driver = new FirefoxDriver();
driver.get("http://demo.guru99.com/test/guru99home/");
driver.manage().window().maximize();
int size = driver.findElements(By.tagName("iframe")).size();
for(int i=0; i<=size; i++){
driver.switchTo().frame(i);
int total=driver.findElements(By.xpath("html/body/a/img")).size();
System.out.println(total);
driver.switchTo().defaultContent();}
public class IndexOfIframe {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://demo.guru99.com/test/guru99home/");
driver.manage().window().maximize();
//driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
int size = driver.findElements(By.tagName("iframe")).size();
for(int i=0; i<=size; i++){
driver.switchTo().frame(i);
int total=driver.findElements(By.xpath("html/body/a/img")).size();
System.out.println(total);
driver.switchTo().defaultContent();}}}
1
0
0
0
0
0
driver.switchTo().frame(0);
driver.findElement(By.xpath("html/body/a/img")).click();
public class SwitchToframe {
public static void main(String[] args) throws NoSuchElementException{
WebDriver driver = new FirefoxDriver();
driver.get("http://demo.guru99.com/test/guru99home/");
driver.manage().window().maximize();
//int size = driver.findElements(By.tagName("iframe")).size();
/*for(int i=0; i<=size; i++){
driver.switchTo().frame(i);
int total=driver.findElements(By.xpath("html/body/a/img")).size();
System.out.println(total);
driver.switchTo().defaultContent(); //switching back from the iframe
}*/
//Commented the code for finding the index of the element
driver.switchTo().frame(0); //Switching to the frame
System.out.println("********We are switched to the iframe*******");
driver.findElement(By.xpath("html/body/a/img")).click();
//Clicking the element in line with Advertisement
System.out.println("*********We are done***************");
}
}
WebDriver driver=new FirefoxDriver();
driver.get("Url");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
int size = driver.findElements(By.tagName("iframe")).size();
System.out.println("Total Frames --" + size);
// prints the total number of frames
driver.switchTo().frame(0); // Switching the Outer Frame
System.out.println (driver.findElement(By.xpath("xpath of the outer element ")).getText());
size = driver.findElements(By.tagName("iframe")).size();
// prints the total number of frames inside outer frame
System.out.println("Total Frames --" + size);
driver.switchTo().frame(0); // Switching to innerframe
System.out.println(driver.findElement(By.xpath("xpath of the inner element ")).getText());
public class FramesInsideFrames {
public static void main(String[] args) {
WebDriver driver=new FirefoxDriver();
driver.get("Url");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
int size = driver.findElements(By.tagName("iframe")).size();
System.out.println("Total Frames --" + size);
// prints the total number of frames
driver.switchTo().frame(0); // Switching the Outer Frame
System.out.println (driver.findElement(By.xpath("xpath of the outer element ")).getText());
//Printing the text in outer frame
size = driver.findElements(By.tagName("iframe")).size();
// prints the total number of frames inside outer frame
System.out.println("Total Frames --" + size);
driver.switchTo().frame(0); // Switching to innerframe
System.out.println(driver.findElement(By.xpath("xpath of the inner element ")).getText());
//Printing the text in inner frame
driver.switchTo().defaultContent();
}
}
Being new to selenium, I learned about iframes and after some inspection I found that the button is located in an iframe which in in an iframe which is in an iframe. I am finally correctly switching to the iframe that contains the button but for some reason the find_element_by_xxx function always says not found whether I use class, id, xpath or
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
def findFrames(driver):
iframes = driver.find_elements_by_xpath('//iframe')
i = 0
index = 0
for iframe in iframes:
print(iframe.get_attribute('src'))
string = iframe.get_attribute('src')
if "tv" in string:
index = i
break
i+=1
print(index)
return iframes, index
def main():
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
#chrome_options.add_argument("/tmp/.com.google.Chrome.sBnz8G/Profile 1")
driver = webdriver.Chrome(options=chrome_options)
driver.get("http://www.investing.com")
try:
#time.sleep(10)
driver.find_element_by_xpath("/html/body/div[5]/header/div[1]/div/div[4]/span[1]/div/a[1]").click()
time.sleep(3)
except:
print("first block")
try:
WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.ID, 'loginPopup')))
print("found")
except:
print("not found")
try:
elem = driver.find_element_by_id("loginFormUser_email")
elem.click()
elem.send_keys("my-email")
elem = driver.find_element_by_id("loginForm_password")
elem.click()
elem.send_keys("my-password")
elem.send_keys(Keys.ENTER)
time.sleep(3)
except:
print("second block")
driver.find_element_by_xpath('//*[@id="navMenu"]/ul/li[5]/a').click()
print("charts clicked")
time.sleep(3)
driver.find_element_by_xpath("/html/body/div[5]/section/div[4]/div[1]/a").click()
print("live charts clicked")
time.sleep(20)
iframes, index = findFrames(driver)
driver.switch_to.frame(iframes[index])
print("switch 1")
iframes, index = findFrames(driver)
driver.switch_to.frame(iframes[index])
print("switch 2")
iframes, index = findFrames(driver)
driver.switch_to.frame(iframes[index])
print("switch 3")
driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/div/div[1]/div[3]/div/span[1]/svg').click() #THIS IS WHERE I GET THE ERROR
print("successfully clicked load")
time.sleep(1.5)
if __name__ == "__main__":
main()
driver.find_element_by_xpath("/html/body/div[5]/section/div[4]/div[1]/a").click()
print("live charts clicked")
WebDriverWait(driver,10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[id^='tvc_frame']")))
WebDriverWait(driver,10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[src$='GB']")))
WebDriverWait(driver,10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[id^='tradingview']")))
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"div.save-load-buttons>span.load"))).click()
print("successfully clicked load")
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
The element with the text as Agree and continue is within multiple <iframe> elements so you have to: Induce WebDriverWait for the desired parent frame to be available and switch to it. Induce WebDriverWait for the desired child frame to be available and switch to it. Induce WebDriverWait for the desired element to be clickable.
<button id="onetrust-accept-btn-handler" tabindex="0">Agree and continue</button>
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.keys import Keys
from time import sleep
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get("http:mail.com")
sleep(3)
try:
iframe = driver.find_elements_by_tag_name('iframe')[o]
driver.switch_to.frame(iframe)
button = iframe.find_element_by_id('onetrust-accept-btn-handler')
#driver.switch_to_default_content()
driver.quit()
except:
print('error')
driver.quit()
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
#updated your URL as your pasted URL wasn't valid
driver.get("https://www.mail.com/consentpage")
#Get iframe 1 - this updates DRIVER to be within that iframe
WebDriverWait(driver, 30).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, ".permission-core-iframe")))
#get iframe 2 - this can only be found when driver is inside the first iframe
WebDriverWait(driver, 30).until(EC.frame_to_be_available_and_switch_to_it((By.TAG_NAME, "iframe")))
#Wait for the button to fully load
button = WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.ID, "onetrust-accept-btn-handler")))
#click it
button.click()
driver.get('https://www.mail.com/consentpage')
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe.permission-core-iframe")))
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[src^='https://plus.mail.com/lt']")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button#onetrust-accept-btn-handler"))).click()
driver.get('https://www.mail.com/consentpage')
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@class='iframe.permission-core-iframe']")))
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[starts-with(@src, 'https://plus.mail.com/lt')]")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@id='onetrust-accept-btn-handler']"))).click()
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
On the page source, search for “ iframe-tags ”. If you find any iframe tags, it means the page includes iframes. Using the SwitchTo().frame function. For a browser to work with several elements in iframes, it is crucial for the browser to identify all the iframes. For this purpose, we need to use the SwitchTo().frame method. This method
<html>
<body>
<div class="box">
<iframe name="iframe1" id="IF1" height="50%" width="50%" src="https://www.browserstack.com"> </iframe>
</div>
<div class="box">
<iframe name="iframe2" id="IF2" height="50%" width="50%" align="left" src="https://www.browserstack.com/"></iframe>
</div>
</body>
</html>
WebDriver driver = new ChromeDriver();
driver.get("https:// url containing i-frames/");
//By finding all the web elements using iframe tag
List<WebElement> iframeElements = driver.findElements(By.tagName("iframeResult"));
System.out.println("Total number of iframes are " + iframeElements.size());
//By executing a java script
JavascriptExecutor exe = (JavascriptExecutor) driver;
Integer noOfFrames = Integer.parseInt(exe.executeScript("return window.length").toString());
System.out.println("No. of iframes on the page are " + numberOfFrames);
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new ChromeDriver();
driver.get("/URL having iframes/");
//Switch by Index
driver.switchTo().frame(0);
driver.quit(); }
WebDriver driver = new ChromeDriver();
driver.get("URL”/"); // URL OF WEBPAGE HAVING FRAMES
//Switch by frame name
driver.switchTo().frame("iframeResult"); //BY frame name
driver.quit();
WebDriver driver = new ChromeDriver();
driver.get("URL”/"); // URL of webpage having frames
//Switch by frame name
driver.switchTo().frame("iframeResult");// Switch By ID
driver.quit();
WebDriver driver = new ChromeDriver();
driver.get("URL”); URL OF WEBPAGE HAVING FRAMES
//First finding the element using any of locator stratedgy
WebElement iframeElement = driver.findElement(By.id("iframeResult"));
//now using the switch command
driver.switchTo().frame(iframeElement);
driver.quit();
WebDriver driver = new ChromeDriver();
driver.get("URL");// URL OF WEBPAGE HAVING FRAMES
//First finding the element using any of locator strategy
WebElement iframeElement = driver.findElement(By.id("iFrameResult"));
//now using the switch command to switch to main frame.
driver.switchTo().frame(0);
//Perform all the required tasks in the frame 0
//Switching back to the main window
driver.switchTo().defaultContent();
driver.quit();
Tour Start here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site
IWebElement iframeSwitch = driver.FindElement(By.XPath("//iframe[contains(@id, 'contentIFrame1')and contains (@title, 'Content Area')]"));
driver.SwitchTo().Frame(iframeSwitch);
driver.FindElement(By.Id("hlx_markertemplateid_ledit")).SendKeys("Test");
<table id="hlx_markertemplateid_lookupTable" class="ms-crm-Lookup" cellspacing="0" cellpadding="0" lookupid="hlx_markertemplateid" style="width: 100%; table-layout: fixed;" aria-labelledby="hlx_markertemplateid_c hlx_markertemplateid_w" controlmode="normal">
<td valign="top">
<div id="hlx_markertemplateid_lookupDiv" class="ms-crm-Lookup ms-crm-InlineLookupEdit ms-crm-Hidden-NoBehavior" role="list" ime-mode="auto" tabindex="0" style="width: 0px;">
<ul class="ms-crm-InlineLookupEdit"></ul>
</div>
<label class="ms-crm-Hidden-NoBehavior" for="hlx_markertemplateid_ledit">Marker Template Required</label>
<input id="hlx_markertemplateid_ledit" class="ms-crm-InlineInput ms-crm-InlineLookupEdit" type="text" ime-mode="auto" maxlength="1000" style="ime-mode: auto;">
</td>
WebElement iframeSwitch = driver.findElement(By.id("contentIFrame1"));
driver.switchTo().frame(iframeSwitch);
System.out.println("Switched");
driver.findElement(By.id("hlx_markertemplateid_ledit")).sendKeys("Test");
actionObject = new Actions(firefoxDrvrInstance);
actionObject.MoveToElement(find element here).Perform();
firefoxDrvrInstance.FindElement(blah blah).Click();
firefoxDrvrInstance.SwitchTo().Frame(firefoxDrvrInstance.FindElement(blah blah));