简体   繁体   English

硒单击XPath按钮

[英]Selenium click on XPath button

I have the following code when I inspect on Chrome. 在Chrome上检查时,我有以下代码。

<span id="button-1111-btnInnerEl" class="x-btn-inner x-btn-inner-center" unselectable="on" style="">New Email</span>

I need to click on the label "New Email", but how should invoke it in Selenium (I'm using Python). 我需要单击标签“ New Email”,但是如何在Selenium中调用它(我正在使用Python)。

def CreateMail():
    EmailButton="//*[contains(text(),'New Email')]"
    driver.find_elements_by_xpath(EmailButton)  // there is no method to enable click.

您可以使用execute_script

driver.execute_script("document.getElementById('button-1111-btnInnerEl').click()")
driver.find_element_by_id("button-1111-btnInnerEl").click()

Thanks all for your help. 感谢你的帮助。 Finally i found the answer to my question.I had to add a wait statement, before finding the key. 最终我找到了问题的答案。在找到密钥之前,我必须添加一个等待语句。 key wasn't present when the page loads, so had to wait a little bit to find the correct key. 页面加载时不存在密钥,因此必须稍等一下才能找到正确的密钥。

def CreateMail():
try:
    element = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.ID, "button-1143-btnInnerEl")))
    driver.find_element_by_id("button-1143-btnInnerEl").click()

except TimeoutException:
    print ("Loading took too much time!")

Your statement : "driver.find_ elements _by_xpath(EmailButton)" . 您的声明:“ driver.find_ 元素 _by_xpath(EmailButton)”。 Click does not work on group of elements. 单击不适用于元素组。 It is actionable only on single element. 它仅对单个元素有效。 So you use a singular finder. 因此,您使用单数查找器。

driver.find_**element**_by_id(EmailButton).click()

希望此XPath对您有用。如果您想使用chrome浏览器验证xpath,只需将此文本粘贴到chrome控制台$x("//*[text()='New Email']")并检查多少个元素使用此XPath找到

 driver.find_elements_by_xpath("//span[text()='New Email']")

As per the HTML you have shared, the id attribute looks dynamic to me. 按照您共享的HTMLid属性对我来说似乎是动态的。 So we must construct a dynamic xpath or css . 因此,我们必须构造一个动态的xpathcss Additionally instead of find_elements we have to use find_element so a single WebElement is returned and we can invoke the click() method. 此外,而不是find_elements我们必须使用find_element因此单个WebElement返回,我们可以调用click()方法。 Finally, if you look at the node properly, the unselectable attribute is on so we will take help of JavascriptExecutor as follows : 最后,如果您正确地查看节点,则unselectable属性处于启用状态,因此我们将按以下方式使用JavascriptExecutor

myElement = driver.find_element_by_xpath("//span[starts-with(@id, 'button-')][@class='x-btn-inner x-btn-inner-center']")
driver.execute_script("arguments[0].click();", myElement);  

Actually there is different way for locating elements but in your case there is a ID, so you can prefer id if its exists 实际上,找到元素的方式不同,但是在您的情况下,有一个ID,因此,如果ID存在,则您可以选择ID

find solution below : 在下面找到解决方案:

driver.find_element_by_id("button-1111-btnInnerEl").click()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM