如何在JAVA中使用Javascript和Selenium更改表单操作

如何在JAVA中使用Javascript和Selenium更改表单操作,javascript,java,html,selenium,Javascript,Java,Html,Selenium,我一直在尝试在JAVA中使用javascript和selenium替换表单的action属性,但无法使其正常工作 这是网站的HTML代码段: </div> <div class="contionue-shopping-wrapper"> <form class="co-formcontinueshopping" action="https://www.yahoo.com" method="post" id="dwfrm_cart_d0jilurhcxpm">

我一直在尝试在JAVA中使用javascript和selenium替换表单的action属性,但无法使其正常工作

这是网站的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>
(注:atc是Selenium chrome Web驱动程序,站点在此阶段加载)

编辑:我想如果我将下面的javascript转换成上面的,它会有效吗

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

这实际上应该是可行的,例如,此代码有效:

@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-FormContinueShapping')
    返回错误,这可能有几个原因,例如站点位于
    iframe
    中。检查是否返回了正确的元素,例如将其记录到控制台
  • document.getElementsByClassName('co-formcontinueshopping')[0]
    正在返回您期望的其他内容,请检查该内容
  • 您正在将操作设置为我在示例中所做的其他操作,例如,我使用了
    '
  • 其他一些东西,比如不同的浏览器(我在Mac上使用了Chrome54.0.2840.98)

log
document.getElementsByClassName('co-formcontinueshapping')[0]。使用
console.log(document.getElementsByClassName('co-formcontinueshapping')[0]。操作将
发送到控制台,查看选择器是否工作。操作)
请检查下面对您的答案的评论。谢谢问题是JavaScript中没有
。因此,您应该在JavaScript中编写字符串链接=“””,或者通过
JavascriptExecutor
执行
。我使用了这个JavaScript:console.log(document.getElementById(document.querySelector(“[id^='dwfrm_cart']”)id.action),它起到了作用。我如何在java中转换选择器,“and”让我感到厌烦。谢谢,我如何将操作设置为我之前创建的字符串变量。我在这里有代码,我会更新我的答案,1秒开始,确保你有
链接
字符串的“in-your”。让我知道它是否适合你,我会相应地更新我的答案。
https://www.adidas.co.uk/on/demandware.store/Sites-adidas-GB-Site/en_GB/Cart-Show/C1360474325
http://www.example.com/