小编典典

如何使用python在selenium中按ID名称的一部分查找元素

selenium

我正在将selenium与python配合使用,现在我想按其ID名称的一部分来定位元素,该怎么办?

例如,现在我已经找到了一个ID为 coption5的商品

sixth_item = driver.find_element_by_id("coption5")

无论如何,我只能使用 coption 来定位此元素吗?


阅读 828

收藏
2020-06-26

共1个答案

小编典典

要查找您所在的元素:

sixth_item = driver.find_element_by_id("coption5")

要仅通过使用 coption 来定位此元素,可以使用以下定位器策略之一:

  • 使用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']")
    
2020-06-26