简体   繁体   English

Python Selenium webdriver 获取 XPATH 和 select 下拉列表

[英]Python Selenium webdriver get XPATH and select dropdown

I've found the word 'Burger' in HTML table with this code我用这段代码在 HTML 表中找到了“Burger”这个词

findRow = driver.find_element(By.XPATH, "//*[contains(text(),'Burger')]").value_of_css_property('#name')
  1. how do I can get XPATH 'Burger'?我怎样才能得到 XPATH 'Burger'?
  2. how do I can select the column beside it (example select 'Fish' beside column 'Burger') and then submit button?我如何才能 select 旁边的列(例如 select '汉堡'列旁边的'鱼')然后提交按钮?

HTML code 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>

In this scenario, you can identify the select list box using xpath following technique.在这种情况下,您可以使用 xpath 以下技术识别 select 列表框。 Use the below xpath to identify select object使用下面的xpath识别select object

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

You can select the option Burger using the below XPath:您可以使用以下 XPath select 选择Burger

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

You can select the options inside select tag using the below XPath:您可以使用以下 XPath select select标签内的选项:

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

Based on the HTML posted, the simplest XPath to find "Burger" would be,根据发布的 HTML,找到“Burger”的最简单的 XPath 是,

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

The XPath to find the SELECT in the cell to the right of the "Burger" cell would be,在“汉堡”单元格右侧的单元格中找到 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

Putting this all together to select "Fish" from the SELECT element next to the "Burger" cell and click Submit,将所有这些放在“汉堡”单元格旁边的 SELECT 元素中的 select“鱼”,然后单击提交,

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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