简体   繁体   中英

Selenium webdriver Xpath with dot (.) in attribute name

I have the following html:

<table id="oTable">
<tbody>
    <tr mote.id="12345">
        <td>Status</td>
        <td>1</td>
    </tr>
    <tr mote.id="54321">
        <td>Status</td>
        <td>2</td>
    </tr>
</tbody>

I want to locate the row with mote.id and click the first td -tag

WebElement element = getDriver().findElement(By.xpath("//tr[@mote.id='12345']/td[1]"));

But I get the following Error:

Bad token, expected: ] got: .

Use this:

findElement(By.xpath("//tbody/tr[1]/td[1]")) 

No need of mote.id.

There are alternative apporaches as well by using

findElements(By.tagName("td")).get(0);

要找到<td>元素,请使用:

WebElement element = getDriver().findElement(By.xpath("//td[contains(text(),'Status')]"));

You need two \\\\ before the dot, first \\ so that the second one gets through, and the second to escape the dot so it becomes literal. Try \\\\. .

Which version of Selenium are you on? I'm on 2.52.0 (latest as of now) and on Python. Your xpath works:

>>> print driver.find_element_by_xpath("//*[@mote.id='12345']").get_attribute('innerHTML')

        <td>Status</td>
        <td>1</td>
>>>
>>> print driver.find_element_by_xpath("//tr[@mote.id='12345']/td[1]").get_attribute('innerHTML')
Status

Alternatively, you could write a helper function to find all the relevant tr elements and then check each one's mote.id for the you want.

>>> def get_mote_by_id(mote_id):
...     elems = driver.find_elements_by_xpath("//*[@id='oTable']/tbody/tr")
...     for elem in elems:
...         if elem.get_attribute('mote.id') == mote_id:
...             return elem
...
>>>
>>> print get_mote_by_id('12345').get_attribute('innerHTML')

        <td>Status</td>
        <td>1</td>

(This is obviously slower than an xpath which matches directly but if it's version issue, then it's a workaround.) And Yes, it's in Python not Java but should be clear what the Java version should do.

PS: Any way you get your devs or product vendor to use mote_id or moteid instead of mote.id ? That would be compliant with attribute names in HTML and XML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM