在Selenium Python中,是否可以选择只有类值的按钮?

2024-09-21 04:23:57 发布

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

在Selenium Python中,是否可以选择只有类值的按钮? html如下:

<button class="secondary option-action ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false"


from selenium import webdriver

browser = webdriver.Firefox()
browser.get(any_url)

你想选那个按钮吗?


Tags: browserdefaultuihtmlseleniumbuttonactionwidget
3条回答

是的,这是可能的。

使用^{}(或find_elements_by_class_name获取多个匹配元素):

browser.find_element_by_class_name('secondary')

也可以使用^{}(或..s变量):

browser.find_element_by_css_selector('.secondary')

或者,您也可以使用find_element_by_xpath,但它需要详细的xpath表达式才能精确:

xpath = "descendant-or-self::*[@class and contains(concat(' ', normalize-space(@class), ' '), ' secondary ')]"
browser.find_element_by_xpath(xpath)

您可以使用css选择器:

driver.find_element_by_css_selector(".secondary")

多个类:

driver.find_element_by_css_selector(".secondary.option-action.ui-button.ui-widget")

您还可以使用:

driver.find_element_by_css_selector("[role=button]")

如果有多个具有相同类的按钮,则可以执行以下操作:

<div id="button-is-here">
<button class="secondary option-action ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false">
</div>

driver.find_element_by_css_selector("#button-is-here .secondary.option-action.ui-button.ui-widget")

如果您只使用类,那么页面中很可能会有另一个具有相同类的按钮,因此有时您必须更具体

我会给你一个和我之前给你的问题类似的答案:

browser.find_element_by_xpath('//input[@class="secondary option-action..."]').click()

不过,您必须自己填写...,或者使用:

browser.find_element_by_xpath('//input[starts-with(@class,"secondary option")]').click()

如果没有任何其他input元素的class属性以“secondary option”开头。。。

相关问题 更多 >

    热门问题