Selenium找到元素并单击它

时间:2016-03-28 12:10:50

标签: python selenium

我正试图让Selenium点击View All Companies按钮,但我不确定我做错了什么。它返回no element found

html代码

<div class="screener-toggles">
  <div class="buttons">
    <span class="button selected" data-name="advanced-screener">Search by Screener<span data-name="advanced-screener" class="arrow selected"></span></span>
    <span class="button" data-name="alpha-factors">Search by Alpha Factors<span data-name="alpha-factors" class="arrow"></span></span>
    <span class="button" data-name="all-companies">View All Companies<span data-name="all-companies" class="arrow"></span></span>
  </div>
</div>

我编写的python代码

element1 = driver.find_elements_by_class_name('View All Companies')
element1.click()
# I have tried all-companies instead of View All Companies as well. But still doesn't work

我不应该使用find_elements_by_class_name吗?

非常感谢任何关于我做错事的建议!

3 个答案:

答案 0 :(得分:2)

尝试xpath "//span[contains(text(),'View All Companies')]"

答案 1 :(得分:1)

是的,您不应使用find_elements_by_class_name而不是find_element_by_class_name

当您希望定位器返回多于1个元素时,使用

find_elements_by_class_name。对于特定元素,仅使用find_element_by_class_name

另一件事是我无法在HTML代码中看到任何类名为View All Companies。请仔细查看您的HTML并仔细选择classname或其他定位器

希望它能帮到你

答案 2 :(得分:1)

View All Companies是文字,而不是课程。尝试使用css_selectorxpath

查看文字
element1 = find_element_by_css_selector('span:contains("View All Companies")')

element1 = find_element_by_xpath('//span[contains(text(), "View All Companies")]')

或包含data-name

all-companies属性
element1 = find_element_by_css_selector('span[data-name*="all-companies"]')