我想在selenium python中单击一个包含class和title的元素。
一个网页包含可重复的类,没有任何id,但有唯一的名称。我想检测并点击这个标题"PaymateSolutions"一旦在页面加载。下面是html标签。我尝试了很多方法,但我最终都犯了错误。我不能按类使用find元素,因为它们不是唯一的。
<div class="MuiGrid-root MuiGrid-item" title="PaymateSolutions">
<p class="MuiTypography-root jss5152 MuiTypography-body1">PaymateSolutions</p>
</div>
我尝试使用XPATH
获得基于标题的驱动元素的几种方法方法1:-
wait = WebDriverWait(driver, 20)
element = wait.until(EC.element_to_be_clickable((By.XPATH,"//class[@title='PaymateSolutions']")))
方法2:-
element2 = (WebDriverWait(driver, 30).until(
EC.visibility_of_element_located((By.XPATH, "//p[@title='PaymateSolutions']")))
)
方法3:-
element2 = (WebDriverWait(driver, 30).until(
EC.visibility_of_element_located((By.XPATH, "//[@title='PaymateSolutions']")))
)
有人能帮帮忙吗?
方法1—"title
"为"div
"标签的属性。所以Xpath应该像下面这样:
//div[@title='PaymateSolutions']
For Approach 2—"p
"标签没有"title
"属性。PaymateSolutions
是p
标签的text
。Xpath应该是这样的:
//p[text()='PaymateSolutions']
For Approach 3—xpath中没有Tag Name
。Xpath应该是:
//*[@title='PaymateSolutions']
Or
//div[@title='PaymateSolutions']
链接参考- Link1, Link2
我们可以像下面这样应用Explicit waits
:
# Imports required for Explicit waits:
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver.get(url)
wait = WebDriverWait(driver,30)
payment_option = wait.until(EC.element_to_be_clickable((By.XPATH,"xpath for PaymateSolutions option")))
payment_option.click()
链接指向显式等待- Link
您一直在尝试的所有XPath似乎都有点错误。请使用下面的XPath:
//div[@title='PaymateSolutions']//p[text()='PaymateSolutions']
代码试验1:
time.sleep(5)
driver.find_element_by_xpath("//div[@title='PaymateSolutions']//p[text()='PaymateSolutions']").click()
代码试验2:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@title='PaymateSolutions']//p[text()='PaymateSolutions']"))).click()
代码试验3:
time.sleep(5)
button = driver.find_element_by_xpath("//div[@title='PaymateSolutions']//p[text()='PaymateSolutions']")
driver.execute_script("arguments[0].click();", button)
代码试验4:
time.sleep(5)
button = driver.find_element_by_xpath("//div[@title='PaymateSolutions']//p[text()='PaymateSolutions']")
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