我正在尝试让硒从下拉菜单中选择特定值。
这里是元素的代码。
<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>
这是网站上的图片,我试图在其中自动选择硒。用于类别“处理单元”。我要它选择托盘。 (第一个选项是“不适用”,第二个选项是“托盘”,第三个选项是“打滑”,等等)
我尝试了以下代码。
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')
您必须使用Select方法,例如:
select_element = Select(driver.find_element_by_xpath(''))
select_element.select_by_value('$1')
也可以使用full Xpath
而不是Xpath
来获取具有selenium
的元素。在您的图片中,您必须获得abs Xpath
。和我说的完整Xpath一样。
要获取硒元素,可以使用此方法:
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中的任何更改都可以使硒找不到元素或找到错误的元素。