Selenium通过Xpath查找第二个元素

2024-10-01 09:21:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在python selenium中使用find_element_by_xpath("//button[@class='sqdOP']"),但我有2Button个类,我需要第二个类,所以只需要第一个类。
我试过下面的代码

find_element_by_xpath("//button[@class='sqdOP'][2]")

find_element_by_xpath("//[button[@class='sqdOP']][2]")

find_element_by_xpath("//button[2][@class='sqdOP']")

find_element_by_xpath("//button[@class='sqdOP'[2]]")

以上这些都不起作用


Tags: 代码byseleniumbuttonelementfindxpathclass
3条回答

使用find_elements_by_xpath而不是find_element_by_xpath来获取元素列表。访问此列表中的特定索引以获取所需元素

您可能正在寻找以下XPath表达式:

find_element_by_xpath("(//button[@class='sqdOP'])[2]"

只需添加()即可获得页面上满足特定属性条件(@class='sqdOP')的第二个button元素

旁注:您的第二次尝试(//[button…)不是有效的XPath表达式。不能用谓词启动表达式。您需要一个元素名或通配符(*

您可以尝试使用JavaScript执行器

WebElement buttton = driver.find_element_by_class_name("sqdOP")
driver.execute_script("arguments[1].click();",buttton)

参数[1]表示单击第二个元素

相关问题 更多 >