Reputation: 146
When I try to get reCaptcha v2
image in selenium, I get no such this element
because the element not in the main page
so how can I get the picture in selenium C#!
_driver.Navigate().GoToUrl("https://www.google.com/recaptcha/api2/demo");
_driver.SwitchTo().Frame(0);
_driver.FindElement(By.Id("recaptcha-anchor")).Click();
Thread.Sleep(5000);
_driver.SwitchTo().Frame(0);
//To get all images in page
IList<IWebElement> images = _driver.FindElements(By.TagName("img"));
MessageBox.Show(images.Count.ToString());
string reCaptchaXpath = "";
foreach (var img in images)
{
if (img.GetAttribute("src").Contains("https://www.google.com/recaptcha/api2/"))
{
reCaptchaXpath = GenerateXpath(img, "");
}
}
Upvotes: 2
Views: 4652
Reputation: 146490
Edit-1
Below code works fine for me and gives 16 images
ChromeDriver _driver;
_driver = new ChromeDriver();
_driver.Url = "https://www.google.com/recaptcha/api2/demo";
Thread.Sleep(5000);
_driver.SwitchTo().Frame(_driver.FindElement(By.CssSelector("iframe[src*='recaptcha']")));
_driver.FindElement(By.ClassName("recaptcha-checkbox-checkmark")).Click();
Thread.Sleep(2000);
//_driver.SwitchTo().Frame(_driver.FindElement(By.CssSelector("iframe[src*='recaptcha']")));
_driver.SwitchTo().DefaultContent();
_driver.SwitchTo().Frame(_driver.FindElements(By.TagName("iframe"))[1]);
images = _driver.FindElements(By.CssSelector("img"));
Console.WriteLine(images.Count.ToString());
Original Answer
Your issue is the below statement
_driver.SwitchTo().Frame(0);
You are assuming there is just one frame. But there are multiple frames
You need to use
_driver.SwitchTo().Frame(_driver.FindElement(By.Css("iframe[src*='recaptcha']")));
Upvotes: 2