【问题标题】:How to change a form action using Javascript and Selenium in JAVA如何在 JAVA 中使用 Javascript 和 Selenium 更改表单操作
【发布时间】:2016-12-01 13:18:02
【问题描述】:

我一直试图在 JAVA 中使用 javascript 和 selenium 替换表单的 action 属性,但我无法让它工作。

这是网站的 sn-p HTML:

</div>
<div class="contionue-shopping-wrapper">
<form class="co-formcontinueshopping" action="https://www.yahoo.com" method="post" id="dwfrm_cart_d0jilurhcxpm">
<fieldset>
<button class="rbk-button-red button-primary bp-black right" type="submit" value="Continue Shopping" name="dwfrm_cart_continueShopping">
<span>Continue Shopping</span>
</button>
</fieldset>
</form>
</div>

这是我在 JAVA 中所做的,试图改变上面的操作

String link = "https://www.google.com"
((JavascriptExecutor)atc).executeScript("document.getElementsByClassName('co-formcontinueshopping')[0].action="+link);

(注意:atc 是 Selenium chrome webdriver,站点在此阶段加载)

编辑:我想如果我将以下 javascript 转换为上面的它会起作用吗?

document.getElementById(document.querySelector("[id^='dwfrm_cart']").id).action = url})()

【问题讨论】:

  • 记录document.getElementsByClassName('co-formcontinueshopping')[0].action到控制台查看选择器是否工作,使用console.log(document.getElementsByClassName('co-formcontinueshopping')[0].action)
  • 请查看下面对您的答案的评论。谢谢
  • 问题是您的 JavaScript 中没有 '。因此,您应该编写 String link = "'google.com'" 或通过 JavascriptExecutor 执行 JavaScript 中的 '

标签: javascript java html selenium


【解决方案1】:

这实际上应该有效,例如此代码有效:

@Test
public void test() throws InterruptedException{

    driver.get("https://www.adidas.co.uk/on/demandware.store/Sites-adidas-GB-Site/en_GB/Cart-Show");
    JavascriptExecutor js=(JavascriptExecutor) driver;

    String link = "'http://www.example.com'"; // notice the extra ' inside the "

    //log the current value of 'action'
    js.executeScript("console.log(document.getElementsByClassName('co-formcontinueshopping')[0].action)");

    //change the value to the value hold by our link
    js.executeScript("document.getElementsByClassName('co-formcontinueshopping')[0].action=" + link);

    //log 'action' again
    js.executeScript("console.log(document.getElementsByClassName('co-formcontinueshopping')[0].action)");

    driver.quit();
}

而浏览器控制台的输出是:

https://www.adidas.co.uk/on/demandware.store/Sites-adidas-GB-Site/en_GB/Cart-Show/C1360474325
http://www.example.com/

所以方法是正确的,只有在你的情况下必须缺少一些东西,例如:

  • document.getElementsByClassName('co-formcontinueshopping') 返回错误,这可能有多种原因,例如该网站位于iframe。检查是否返回了正确的元素,例如将其记录到控制台。
  • document.getElementsByClassName('co-formcontinueshopping')[0] 正在返回您所期望的其他内容,请检查一下
  • 您正在将操作设置为我在示例中所做的其他操作,例如我用的是''
  • 其他东西,例如不同的浏览器(我在 Mac 上使用的是 Chrome 54.0.2840.98)

【讨论】:

  • 我改用了这个 javascript:console.log(document.getElementById(document.querySelector("[id^='dwfrm_cart']").id).action) 并且它有效。如何在 java 中转换选择器," 和 ' 让我失望。谢谢
  • 以及如何将操作设置为我之前创建的字符串变量。
  • 我的代码在这里工作,我会更新我的答案,1 秒
  • 在这里,确保您的 " 中包含 link 字符串的 '。
  • 让我知道它是否适合你,我会相应地更新我的答案。
猜你喜欢
  • 2011-07-18
  • 2018-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多