【问题标题】:Python Selenium, how to find an element NOT containing a stringPython Selenium,如何找到不包含字符串的元素
【发布时间】:2019-06-29 11:50:19
【问题描述】:

基本上我已经拥有的是一段代码,它可以找到页面上包含关键字 Matty Matheson Hood 的所有 selenium 元素(见下文):

keyword = 'Matty Matheson Hood'
list = driver.find_elements_by_xpath("//*[contains(text(), '" + keyword + "')]")
print(list)

现在这工作正常,但是,它返回 4 个元素,我试图通过删除包含关键字 Tie Dye

的元素将其缩小到 1

简而言之,我想知道是否可以使用类似于上面的内容,而是使用 not contains,是否可以将包含和不包含合并到 1 个搜索中? p>

所以找出所有包含 Matty Matheson Hood 但包含 Tie Dye 的元素(应该只有 1 个)。

感谢任何帮助!

【问题讨论】:

    标签: python-3.x selenium xpath


    【解决方案1】:

    这是一个纯 xpath,它将只返回包含 Matty Matheson Hood 而不包含 Tie Dye 的元素。

    //*[contains(text(), 'Matty Matheson Hood')][not(contains(text(),'Tie Dye'))]
    

    截图:

    【讨论】:

      【解决方案2】:

      我们可以使用列表推导并从列表中删除我们不再需要的所有我们想要的项目。

      选项可能如下:

      some_list = driver.find_elements_by_xpath("//*[contains(text(), '" + keyword + "')]")
      
      matching = [s for s in some_list if "Tie Dye" in s]
      

      列表推导用于从其他可迭代对象创建新列表。

      当列表推导返回列表时,它们由包含表达式的括号组成,该表达式与 for 循环一起为每个元素执行以遍历每个元素。

      这是基本语法:

      new_list = [expression for_loop_one_or_more conditions]
      

      【讨论】:

      • 感谢您的建议,忘记在这里查看任何可能的解决方案,但似乎我之前找到了我的解决方案:)
      【解决方案3】:

      我设法通过多列表解决方法解决了我的问题:

          positive_list = driver.find_elements_by_xpath("//*[contains(text(), '" + positive_keyword + "')]")
          negative_list = driver.find_elements_by_xpath("//*[contains(text(), '" + negative_keyword + "')]")
      
          result_list = [item for item in positive_list if item not in negative_list]
      

      它可能不是最有效的系统,但它适用于我的目的。如果您发现任何方法,请随时添加更有效的方法:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-05
        • 1970-01-01
        • 2012-09-01
        • 1970-01-01
        • 2021-12-17
        • 2018-11-07
        • 2019-06-20
        • 1970-01-01
        相关资源
        最近更新 更多