Is it possible to locate element by partial id match in Selenium

后端 未结 5 976
旧巷少年郎
旧巷少年郎 2020-11-28 08:36

I am trying to locate elements with generated ids wherein some part of the ID is known; for example:

id=\"page_x002e_x0023_default-create-firstname\"
         


        
相关标签:
5条回答
  • 2020-11-28 09:02

    This works with selenium vba

     .FindElementsByXPath( "//*[contains(@class, 'unique-string')]" )
    
    0 讨论(0)
  • 2020-11-28 09:06

    You can try out this in Java-Selenium: you can use either ends-with() or contains(). I think Both should work.

    driver.findElement(By.xpath("//*[ends-with(@id,'_default-create-firstname')]"));
    driver.findElement(By.xpath("//*[contains(@id, '_default-create-firstname')]"));
    
    0 讨论(0)
  • 2020-11-28 09:08

    If you want to go down the xpath route then you could use contains(), like this:

    //*[contains(@id,'_default-create-firstname')]
    

    This will search the entire page for an id that contains the text "_default-create-firstname". It can be easily made more specific

    0 讨论(0)
  • 2020-11-28 09:14

    You can apply an ends-with CSS selector:

    By.cssSelector("[id$=default-create-firstname]")
    

    Update

    Some time went by since the answer was posted. Here some update from the linked mozilla developer page and comments below:

    New use By.css instead of By.cssSelector

    By.css("[id$=default-create-firstname]")
    

    Also see the four possibilities of

    • beginning with
    • anywhere inside
    • anywhere inside regardless capitalization
    • end with

    /* Internal links, beginning with "#" */
    a[href^="#"] {
      background-color: gold;
    }
    
    /* Links with "example" anywhere in the URL */
    a[href*="example"] {
      background-color: silver;
    }
    
    /* Links with "insensitive" anywhere in the URL,
       regardless of capitalization */
    a[href*="insensitive" i] {
      color: cyan;
    }
    
    /* Links that end in ".org" */
    a[href$=".org"] {
      color: red;
    }
    
    0 讨论(0)
  • 2020-11-28 09:15

    Work one

    driver.find_element_by_xpath("//*[contains(@id, 'jobs-search-box-keyword-id')]")
    

    Not work ones, all got the same error, TypeError: 'str' object is not callable

    1. driver.find_element(By.XPATH("//*[contains(@id, 'jobs-search-box-keyword-id')]")).text
    
    2. driver.find_element(By.XPATH("//*[contains(@id, 'jobs-search-box-keyword-id')]").text).text
    
    3. driver.find_element(By.XPATH("//*[contains(@id, 'jobs-search-box-keyword-id')]")).get_attribute("innerHTML")
    
    4. driver.find_element(By.XPATH("//*[contains(@id, 'jobs-search-box-keyword-id')]").get_attribute("innerHTML")).get_attribute("innerHTML")
    

    I use python 3.7.6, selenium 3.141.0

    0 讨论(0)
提交回复
热议问题