【问题标题】:How to find element by part of its id name in selenium with python如何使用python在selenium中通过其id名称的一部分查找元素
【发布时间】:2020-04-25 11:15:53
【问题描述】:

我在 python 中使用 selenium,现在我想通过它的 id 名称的一部分来定位一个元素,我该怎么办?

例如,现在我已经通过 id 名称 coption5 找到了一个项目:

sixth_item = driver.find_element_by_id("coption5")

有没有我只能使用 coption 来定位这个元素?

【问题讨论】:

  • 使用 XPATH 的“包含”方法:guru99.com/xpath-selenium.html#6
  • 使用css:[id^="coption"]
  • @Guy 这个问题是关于定位器 XpathCss 的,任何你想对 Xpath 隐藏问题的原因i> 和 Css 贡献者删除了这些标签?
  • @DebanjanB 使用 xpath 和 css_selector 是解决方案,而不是问题。
  • @Guy 那么你觉得这个问题到底是怎么回事:) 除了 CssXpath之外,Selenium 还有其他方法吗? >

标签: python selenium selenium-webdriver xpath css-selectors


【解决方案1】:

要找到您所在的元素:

sixth_item = driver.find_element_by_id("coption5")

要仅使用 coption 定位此元素,您可以使用以下任一Locator Strategies

  • 使用XPATHstarts-with()

    sixth_item = driver.find_element_by_xpath("//*[starts-with(@id, 'coption')]")
    
  • 使用XPATHcontains()

    sixth_item = driver.find_element_by_xpath("//*[contains(@id, 'coption')]")
    
  • 使用CSS_SELECTOR^(开头的通配符):

    sixth_item = driver.find_element_by_css_selector("[id^='coption']")
    
  • 使用CSS_SELECTOR*(包含通配符):

    sixth_item = driver.find_element_by_css_selector("[id*='coption']")
    

参考

您可以在以下位置找到有关动态 CssSelectors 的详细讨论:

【讨论】:

  • 非常感谢您的回复,但在我的情况下它现在不起作用。我会继续努力!
  • 先生你能帮我解决这个问题吗stackoverflow.com/questions/59653599/…
  • 太有用了!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-24
  • 2019-08-16
  • 1970-01-01
  • 2015-04-18
  • 2021-08-19
  • 1970-01-01
相关资源
最近更新 更多