Python Selenium Web驱动程序获取XPATH并选择下拉列表

ne5o7dgx  于 2023-01-29  发布在  Python
关注(0)|答案(3)|浏览(150)

我已经找到了这个词'汉堡'在HTML表与此代码

findRow = driver.find_element(By.XPATH, "//*[contains(text(),'Burger')]").value_of_css_property('#name')

1.我怎样才能得到XPATH汉堡包?
1.我如何选择它旁边的列(例如选择列"汉堡"旁边的"鱼"),然后提交按钮?
HTML代码

<tbody>
        <tr>
            <td>..</td>
            <td>.....</td>
        </tr>
        <tr>
            <td>Burger</td>
            <td>
                <select class="form-control input-sm" id="sel222" name="sel222" type="68" group="433" onchange="count(this)">
                    <option value="1">Vegetables</option>
                    <option value="2">Fish</option>
                    <option value="3">Beef</option>
                </select>
            </td>
        </tr>       
    </tbody>
</table>
              <button type="button" class="btn btn-primary" id="submit"><span class="fa fa-save"></span> Save</button>
hec6srdp

hec6srdp1#

根据发布的HTML,查找“Burger”的最简单XPath是,

//td[text()='Burger']

在“Burger”单元格右侧的单元格中查找SELECT的XPath是,

//td[text()='Burger']/following-sibling::td/select
  ^ the XPath to find the TD that contains "Burger", from above
                      ^ then find the sibling TD
                                            ^ then the SELECT child of the sibling

将所有这些放在一起,从“Burger”单元格旁边的SELECT元素中选择“Fish”,然后单击Submit,

from selenium.webdriver.support.ui import Select

select = Select(driver.find_element(By.XPATH, "//td[text()='Burger']/following-sibling::td/select"))
select.select_by_visible_text("Fish")
driver.find_element(By.ID, "submit").click()
izkcnapc

izkcnapc2#

在这种情况下,您可以使用xpath跟踪技术来标识选择列表框。

//td[contains(.,'Burger')]/following::select
rjee0c15

rjee0c153#

您可以使用以下XPath选择选项Burger

.//td[text()='Burger']

您可以使用以下XPath选择select标记内的选项:

.//td[text()='Burger']//parent::tr//select/option

相关问题