【问题标题】:selenium count elements of xpathxpath的硒计数元素
【发布时间】:2013-08-23 00:23:46
【问题描述】:

我有一个包含许多下载链接的表格的网页 我想让 selenium 点击最后一个:

表:

item1 Download
item2 Download
item3 Download

selenium 必须点击Download 下一个item3

我使用xpath查找所有元素然后以这种方式获取返回数组或dict的大小

x = bot._driver.find_element_by_xpath("//a[contains(text(),'Download')]").size()

但我总是得到这个错误

TypeError: 'dict' object is not callable

我尝试使用get_xpath_count 方法,但该方法在 python 中的 selenium 中不存在!

我想过另一种解决方案,但我不知道该怎么做,如下所示

x = bot._driver.find_element_by_xpath("(//a[contains(text(),'Download')])[size()-1]")

x = bot._driver.find_element_by_xpath("(//a[contains(text(),'Download')])[last()]")

或者其他的

【问题讨论】:

  • 可以打印bot._driver.find_element_by_xpath("//a[contains(text(),'Download')]")的结果吗?
  • size 是一个属性。如果您想查找与您的xpath 匹配的所有项目,请使用find_elements_by_xpath(注意s)。
  • @kroolik,是的,它现在与“s”一起工作,但它返回一个空列表,size() 不起作用,但 len(x) 起作用。另一方面bot._driver.find_element_by_xpath("(//a[contains(text(),'Download')])[5]").click() without "s" 有效!那么为什么find_elements_by_xpath 返回空列表:/

标签: python xpath selenium web2py


【解决方案1】:

最好的方法是使用 JavaScript 并按类名查找元素

self.bot._driver.execute_script("var e = document.getElementsByClassName('download'); e[e.length-1].click()")

来源: http://de.slideshare.net/adamchristian/javascript-testing-via-selenium

【讨论】:

    【解决方案2】:

    虽然get_xpath_count("Xpath_Expression")在Python中不存在,但是可以使用

    len(bot._driver.find_element_by_xpath("//a[contains(text(),'Download')]"))
    

    实现元素个数,然后遍历then,使用

    something.xpath(//a[position()=n])
    

    在哪里

    n < len(bot._driver.find_element_by_xpath("//a[contains(text(),'Download')]"))

    【讨论】:

    • 我使用 find_elements_by_xpath 而不是 find_element_by_xpath。该方法有复数。
    • 非常感谢,这对我有帮助
    【解决方案3】:

    使用 find_elements_by_xpath 获取相关元素的数量

    count = len(driver.find_elements_by_xpath(xpath))
    

    然后点击最后一个元素:

    elem = driver.find_element_by_xpath(xpath[count])
    elem.click()
    

    注意:find_elements_by_xpath 在第一个代码 sn-p 中是复数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-03
      • 1970-01-01
      • 2011-11-15
      • 1970-01-01
      • 2021-11-24
      • 2019-05-04
      • 2014-08-01
      • 1970-01-01
      相关资源
      最近更新 更多