Choose element by partial ID using Selenium with python?

bing picture bing · Apr 6, 2013 · Viewed 19k times · Source

I am trying to reach an web element in Selenium in Python 2.7. The element ID is like this:

cell.line.order(240686080).item(250444868).unitCost

The first number string '240686080' is known, but the second number '250444868' is unknown beforehand.

I tried to reach it by something like this.

from selenium import webdriver
driver = webdriver.Firefox()
driver.get("somewebsite.com")
driver.find_elements_by_id('input.line.order(240417939).item('+ '\d{9}'+').unitCost')

So my questions is, is there anyway we can search and reach this element only with part of the ID known?

I found similar question answered below, but it was in C#. And unfortunately, I don't know C#.

Finding an element by partial id with Selenium in C#

Thank you in advance!

Edited 4/8

The element is coded like this:

<td id="cell.line.order(240417939).item(250159165).unitCost" class="or_monetarydata">
    <input id="input.line.order(240417939).item(250159165).unitCost" type="hidden" value="135.00" 
    name="order(240417939).item(250159165).unitcost"></input>

    135.00

    </td>

I could get the element list by

value=driver.find_elements_by_xpath("//*[contains(@id, 'input.line.order(240417939)')]")

Thank you!

Answer

Arran picture Arran · Apr 6, 2013

Although the answer is in C#, the underlying solution is still the same, by using CSS selectors:

driver.find_elements_by_css_selector('input[id*='cell.line.order(240686080)']')

or XPath will also be able to do this:

driver.find_elements_by_xpath('//*[contains(@id, 'cell.line.order(240686080)')]')