18910140161

JavaScript-如何在Python中使用Selenium单击没有类、ID或名称的OnClick-堆栈溢出

顺晟科技

2022-10-18 12:51:47

180

我试图找到一种点击“ X ”的方法。但是我找不到点击这个按钮的方法。

元素副本:

<div style="cursor: pointer; float:right; border-radius: 3px; background-color: red; font-size: 10px; color: white; height: 15px; width:15px; line-height: 15px;" onclick="fecharModal();">X</div>

XPath:

//*[@id="meu_modal"]/div

CSS选择器:

#meu_modal > div

已尝试:

driver.find_element_by_css_selector("a[onclick*=fecharModal]").click();

进口:

<块引用>

从Selenium从selenium.webdriver.common.keys导入WebDriver从Selenium.WebDriver.Support.UI导入密钥导入选择Selenium.WebDriver.Common.By导入方式Selenium.WebDriver.Support.UI从导入WebDriverWaitSelenium.WebDriver.Support将预期的_条件作为EC从Selenium.Common.Exceptions从导入NoSuchElementExceptionSelenium.WebDriver.Common.Action_Chains导入ActionChains导入时间enter code here


顺晟科技:

这似乎是一个有角度的基础应用程序,主要是WebDriverWait应该做这项工作,但仍然下面的解决方案illustarte在Selenium中单击Web元素的所有方法代码试用版2是更可取的最佳实践。

我将使用这个XPath

//div[@onclick='fecharModal();' and text()='X']

代码试验1:

time.sleep(5)
driver.find_element_by_xpath("//div[@onclick='fecharModal();' and text()='X']").click()

代码试验2:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@onclick='fecharModal();' and text()='X']"))).click()

代码试验3:

time.sleep(5)
button = driver.find_element_by_xpath("//div[@onclick='fecharModal();' and text()='X']")
driver.execute_script("arguments[0].click();", button)

代码试验4:

time.sleep(5)
button = driver.find_element_by_xpath("//div[@onclick='fecharModal();' and text()='X']")
ActionChains(driver).move_to_element(button).click().perform()

进口:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains

PS:如果我们在dev tools中有唯一的条目,请检查HTML DOM(Google Chrome)。

检查

步骤:

Press F12 in Chrome->;转到element部分->;执行CTRL + F->;然后粘贴xpath,并查看所需的element是否突出显示1/1匹配节点。

假设您提供的XPath是准确的,我建议您尝试这段代码,这可能对您有用。

yourEle = driver.find_element_by_xpath("//*[@id='meu_modal']/div")
driver.execute_script("arguments[0].click();", yourEle)

  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航