Как построить XPath для включения определенных элементов из HTML? - PullRequest
0 голосов
/ 29 января 2019

У меня есть таблица, и я хочу только выбрать кнопки на этой таблице.Как мы видим, в этой таблице всего 4 кнопки:

enter image description here

Я создал следующие Xpath для фильтрации этих 4 кнопок и других кнопок на странице:

//*[@id="studentListTable"]/thead/tr/th[contains(., "Actions")]//following::button  | //*[@id="studentListTable_info"]//preceding::button 
  • Ссылка @ id = "studentListTable_info"к тексту «Показано от 1 до 3 из 3 записей».

Но это не работает.
Этот XPath фактически находит все кнопки на странице независимо от их расположения.

Что здесь не так?

Как я могу это исправить, чтобы только четыре кнопки были расположены этимвыражение?

Фрагмент HTML-кода:

<div _ngcontent-c7="" appcard="" class="card">
    <div _ngcontent-c7="" class="card-header">
        <h5 _ngcontent-c7="">Student list <!----></h5></div>
    <ul _ngcontent-c7="" class="card-actions">
        <li _ngcontent-c7="">
            <button _ngcontent-c7="" appcardfullscreen="" class="card-action">
                <i _ngcontent-c7="" class="fa fa-arrows-alt"></i></button></li>
        <li _ngcontent-c7="">
            <button _ngcontent-c7="" appcardcollapse="" class="card-action icon-collapse"><i _ngcontent-c7="" class="material-icons">expand_more</i></button></li></ul>
    <!---->
    <div _ngcontent-c7="" class="card-body">
        <div id="studentListTable_wrapper" class="dataTables_wrapper no-footer">
            <div class="dataTables_length" id="studentListTable_length">
                <label>Show <select name="studentListTable_length" aria-controls="studentListTable" class="">
                    <option value="10">10</option>
                    <option value="25">25</option>
                    <option value="50">50</option><option value="100">100</option>
                </select> entries</label></div>
            <div id="studentListTable_filter" class="dataTables_filter">
                <label>Search:<input type="search" class="" placeholder="" aria-controls="studentListTable"></label>
            </div>
            <table _ngcontent-c7="" class="table table-striped dataTable no-footer" datatable="" id="studentListTable" role="grid" aria-describedby="studentListTable_info">
            <thead _ngcontent-c7="">
            <tr _ngcontent-c7="" role="row">
                <th _ngcontent-c7="" class="sorting_asc" tabindex="0" aria-controls="studentListTable" rowspan="1" colspan="1" aria-sort="ascending" aria-label="Student ID: activate to sort column descending" style="width: 101px;">Student ID</th>
                 <th _ngcontent-c7="" class="sorting_disabled" rowspan="1" colspan="1" aria-label="Actions" style="width: 106px;">Actions</th></tr>
            </thead><!----><tbody _ngcontent-c7=""><!---->
            <tr _ngcontent-c7="" role="row" class="odd">
                <td _ngcontent-c7="" class="sorting_1">123456</td>
                 <td _ngcontent-c7="">
                    <a href="unsafe:javascript:void(0)">
                        <i class="material-icons text-warning">info</i> Not Started</a></td>
                <td _ngcontent-c7="">Null</td>
                <td _ngcontent-c7="" class="text-left"><!----><div _ngcontent-c7="">
                    <button _ngcontent-c7="" class="btn btn-sm btn-sm-action mr-2 btn-outline-info" container="body" placement="left" popoverclass="btn-popover" triggers="mouseenter:mouseleave" type="button" tabindex="0">
                        <i _ngcontent-c7="" class="fa fa-arrow-right"></i></button></div><!----><!----><!----></td></tr>
            <tr _ngcontent-c7="" role="row" class="even">
                <td _ngcontent-c7="" class="sorting_1">153246</td>
                 <td _ngcontent-c7=""><a href="unsafe:javascript:void(0)"><i class="fa fa-unlock mr-2"></i>In Progress</a></td>
                <td _ngcontent-c7="">Herndon MS</td>
                <td _ngcontent-c7="" class="text-left"><!----><!----><div _ngcontent-c7=""><!----><div _ngcontent-c7="" class="d-flex align-items-center">
                    <button _ngcontent-c7="" class="btn btn-sm btn-sm-action mr-2 btn-outline-info col" container="body" placement="left" popoverclass="btn-popover" triggers="mouseenter:mouseleave" type="button" tabindex="0">
                        <i _ngcontent-c7="" class="fa fa-pencil"></i></button>
                    <button _ngcontent-c7="" class="btn btn-sm btn-sm-action mr-2 btn-outline-danger col" container="body" placement="left" popoverclass="btn-popover" triggers="mouseenter:mouseleave" type="button">
                        <i _ngcontent-c7="" class="fa fa-trash-o"></i></button></div><!----></div><!----><!----></td></tr>
            <tr _ngcontent-c7="" role="row" class="odd">
                <td _ngcontent-c7="" class="sorting_1">234135</td>
                 <td _ngcontent-c7="" class="text-left"><!----><!----><!---->
                    <div _ngcontent-c7="">
                        <button _ngcontent-c7="" class="btn btn-sm btn-sm-action mr-2 btn-outline-info" container="body" placement="left" popoverclass="btn-popover" triggers="mouseenter:mouseleave" type="button" tabindex="0">
                            <i _ngcontent-c7="" class="fa fa-eye"></i></button></div><!----></td></tr></tbody><!----><!----><!----></table>
            <div class="dataTables_info" id="studentListTable_info" role="status" aria-live="polite">Showing 1 to 3 of 3 entries</div>
            <div class="dataTables_paginate paging_simple_numbers" id="studentListTable_paginate">
                <a class="paginate_button previous disabled" aria-controls="studentListTable" data-dt-idx="0" tabindex="0" id="studentListTable_previous">Previous</a>
                <span>
                    <a class="paginate_button current" aria-controls="studentListTable" data-dt-idx="1" tabindex="0">1</a>
                </span>
                <a class="paginate_button next disabled" aria-controls="studentListTable" data-dt-idx="2" tabindex="0" id="studentListTable_next">Next</a></div></div></div></div>

Ответы [ 6 ]

0 голосов
/ 31 января 2019

Вы можете выбрать кнопки с помощью Student Id, используя приведенный ниже xpath, например, с 153246 id:

//table[@id='studentListTable']//tr[@role='row' and ./td[@class='sorting_1' and .='153246']]//button
0 голосов
/ 31 января 2019

BUTTON s, которые вы хотите, являются единственными кнопками внутри таблицы, и таблица имеет идентификатор studentListTable, поэтому все, что вам нужно, это дочерние элементы BUTTON s идентификатора.

FromHTML, который вы предоставили, будет работать что-то простое, подобное приведенному ниже.

XPath

//[@id='studentListTable']//button

Селектор CSS

#studentListTable button
0 голосов
/ 30 января 2019

Несколько точек:

  • Кнопки в первом и третьем ряду находятся в пределах class="odd"
  • Две кнопки во втором ряду находятся в пределах class="even"

Чтобы отфильтровать эти 4 кнопки, вы можете использовать следующее решение на основе XPath :

"//table[@class='table table-striped dataTable no-footer' and @id='studentListTable']//tbody//tr[@class= 'odd' or @class='even']//td[@class='text-left']//button"

Снимокрезультата сопоставления с помощью xpath checker:

matching_xpath

Примечание : Вы не упомянули языковая привязка , которую вы используете, чтобы элементы были угловыми элементами, чтобы найти элемент, который вы должны заставить WebDriverWait , чтобы элемент был активным .

0 голосов
/ 30 января 2019

Если я правильно понимаю, заголовок означает, что вы хотите объединить 2 попытки XPath-выражения, чтобы получить кнопки, расположенные после th, содержащие текст «Действия» и перед div сid "studentListTable_info" :

//*[@id="studentListTable"]/thead/tr/th[contains(., "Actions")]//following::button[
    following::*[@id="studentListTable_info"]
]
0 голосов
/ 30 января 2019

Вы можете использовать следующее выражение XPath-1.0:

//table[@id="studentListTable" and thead/tr/th/text() =  "Actions"]/tbody/tr/td[@class="sorting_1"]

, чтобы выбрать следующие три элемента:

<td _ngcontent-c7="" class="sorting_1">123456</td>
<td _ngcontent-c7="" class="sorting_1">153246</td>
<td _ngcontent-c7="" class="sorting_1">234135</td>

Чтобы продолжить, чтобы получить четыре button св эти три table с будет работать следующий XPath:

//table[@id="studentListTable" and thead/tr/th/text() =  "Actions"]/tbody/tr/td[@class="sorting_1"]/../../tr/td//button

Его результат состоит из следующих четырех элементов:

<button ... type="button" tabindex="0">
    <i _ngcontent-c7="" class="fa fa-arrow-right"/>
</button>
<button ... type="button" tabindex="0">
    <i _ngcontent-c7="" class="fa fa-pencil"/>
</button>
<button ... type="button">
    <i _ngcontent-c7="" class="fa fa-trash-o"/>
</button>
<button ... type="button" tabindex="0">
    <i _ngcontent-c7="" class="fa fa-eye"/>
</button>
0 голосов
/ 30 января 2019
  1. Трудно ответить на ваш первый вопрос, что там не так.
    Вы используете | и два разных id с, и, возможно, это не совсем правильно.
    Ивы использовали thead элемент в вашем Xpath.Несмотря на то, что все кнопки расположены на tbody.В любом случае, ваш локатор получает все кнопки HTML с этой страницы.

  2. Я пытался изменить Xpath следующим образом:

// таблица // кнопка

И это сработало хорошо:

enter image description here

Однако, это не очень хорошо Xpath .
Так что попробуйте привязать его к ближайшему id.После обновления оно может выглядеть следующим образом:

// div [@ id = 'studentListTable_wrapper'] // table // button

Результат оценки тот же.

И гораздо более избыточной версией будет (не рекомендуется использовать, только для примера):

// div [@ id = 'studentListTable_wrapper'] // table /tbody / tr / td / div // button

Кстати, на мой взгляд, гораздо лучше использовать такие локаторы, как:

// div [@ id = '... ']

вместо:

// * [...]

Трудно понять, может ли это быть причинойнеправильного выбора.
Наверняка это гораздо больше читабельный и легче понять в будущей поддержке.

...