首页 > 解决方案 > 尝试使用下拉菜单(选择元素)使硒发挥作用

问题描述

我试图让硒从下拉菜单中选择一个特定的值。

这是元素的图片。 在此处输入图像描述

这是元素的代码。

<select _ngcontent-c31="" class="input productEntry ng-valid ng-touched ng-dirty" formcontrolname="handlingUnit" tabindex="1022" style="">
    <option _ngcontent-c31="" value="0">N/A</option>
    <!---->
    <option _ngcontent-c31="" value="1" class="ng-star-inserted">Pallet</option>
    <option _ngcontent-c31="" value="2" class="ng-star-inserted">Skid</option>
    <option _ngcontent-c31="" value="3" class="ng-star-inserted">Loose</option>
    <option _ngcontent-c31="" value="4" class="ng-star-inserted">Other</option>
    <option _ngcontent-c31="" value="5" class="ng-star-inserted">Gaylord</option>
    <option _ngcontent-c31="" value="6" class="ng-star-inserted">Master Bundles</option>
    <option _ngcontent-c31="" value="7" class="ng-star-inserted">Carrier</option>
</select>

这是我试图让硒自动选择的网站图片。它适用于“处理单元”类别。我希望它选择托盘。(第一个选项是 N/A,第二个选项是 Pallet,第三个选项是 Skid 等)

界面

我试过下面的代码。

from selenium.webdriver.support.ui import Select

select_element = Select(driver.find_element(By.XPATH, "//select[@class='input productEntry ng-valid ng-dirty ng-touched']"))
select_element.select_by_value('$1')

这一行导致我的其余代码出错。用硒编码选择元素的最佳方法是什么?

更新的解决方案

select_element = Select(driver.find_element_by_xpath('/html[1]/body[1]/app-root[1]/div[1]/div[1]/app-record[1]/div[1]/div[2]/div[1]/app-record-quoting[1]/div[1]/app-record-product-list-panel[1]/form[1]/div[3]/div[1]/div[3]/div[1]/select[1]'))
select_element.select_by_value('1')

标签: python-3.xseleniumxpathbrowser-automation

解决方案


您必须像这样使用 Select 方法:

select_element = Select(driver.find_element_by_xpath(''))
select_element.select_by_value('$1')

您也可以使用full Xpath而不是Xpath使用selenium. 在你的照片中,你必须得到abs Xpath. 它与我所说的完整 Xpath 相同。

要使用 selenium 获取元素,您可以使用以下命令:

driver.find_element_by_xpath('')

如果你想点击它,使用这个:

driver.find_element_by_xpath('').click()

如果要获取元素文本,请使用以下命令:

driver.find_element_by_xpath('').text

如果要在元素中写入文本,请使用以下命令:

driver.find_element_by_xpath('').send_keys('')

您可以同时使用 abs 和 rell Xpath,但是 abs Xpath 中的问题是 html 中的任何更改都可能使 selenium 找不到元素或找到错误的元素。


推荐阅读