首页 > 解决方案 > 在 href 按钮 HTML 上使用 Click()

问题描述

我正在做一个 selenium 项目,一旦它填写了一个文本框,点击下一页,就会出现一个验证码。首先你需要验证,然后验证码就会出现。它只是页面中间的一个弹出框,它使其他所有内容都无法点击,并在其后面的页面上覆盖着一层白雾。单击验证后,我已经有了解决验证码的方法。我遇到的问题是,使用我尝试过的方法,webdriver 似乎找不到这个按钮的任何痕迹。no such element exception尝试使用时,我总是得到一个click(). 我试过了wait.until(ExpectedConditions.elementToBeClickable(By.id("home_children_button"))).click();wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.id("home_children_button")))).click();我也试过thread.sleep(Num)在谷歌上放一个而不是使用等待,以及许多其他方法。然后当我对href按钮进行一些研究时,我发现人们推荐使用By.linkText. 所以我尝试了我之前尝试过的所有方法,但仍然无法找到元素。我在谷歌上找不到其他任何东西,所以我想我会寻求帮助。我已经附加了我目前正在查看的按钮的 HTML 代码,以及网站的链接。不幸遇到此页面,您必须注册一个帐户。这个页面通常会在我放入 DOB 后出现。感谢您提供的任何澄清。

<a href="javascript:;" id="home_children_button" class="sc-bdfBwQ jXXvQg sc-kEjbxe hVNnSn">Verify</a>

https://account.battle.net/creation/flow/creation-full

我试过的代码:

        wait2.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("fc-iframe-wrap")));
        wait2.until(ExpectedConditions.elementToBeClickable(By.id("home_children_button"))).click();
        WebDriverWait wait2 = new WebDriverWait(driver, 10);
        wait2.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("CaptchaFrame")));
        wait2.until(ExpectedConditions.elementToBeClickable(By.id("home_children_button"))).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("home_children_button"))).click();

wait.until(ExpectedConditions.elementToBeClickable(By.id("home_children_button"))).click();,

wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.id("home_children_button")))).click();

Thread.sleep(5000) //wait for it to pop up
driver.findElement(By.id("home_children_button"))).click();

随着尝试使用By.linkText.

解决方案:在被告知它是 iframe 后,我仔细查看了 HTML,发现有多个 iframe。所以我等待切换它们以便单击按钮。

        WebDriverWait wait2 = new WebDriverWait(driver, 20);
        wait2.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("/html/body/div[4]/iframe")));
        wait2.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("/html/body/div/div[1]/div/iframe")));
        wait2.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("/html/body/div[1]/div[2]/div[1]/iframe")));
        
        wait2.until(ExpectedConditions.elementToBeClickable(By.id("home_children_button"))).click();

标签: javaseleniumhrefcaptcha

解决方案


正如我所怀疑的,它在iframe中,您需要切换驱动程序的焦点以与验证按钮进行交互:

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("CaptchaFrame")));
wait.until(ExpectedConditions.elementToBeClickable(By.id("home_children_button"))).click();

一旦你完成它,你可能想要使用defaultContent()

driver.switchTo().defaultContent();

推荐阅读