首页 文章

Python Selenium - 使用存储变量选择下拉选项

提问于
浏览
0

我编写了一个python selenium脚本,从下拉列表中选择一个状态值 . 下拉元素的HTML复制如下:

<div class="hQSHyh4QFG0Xh0d-6pxTF" tabindex="0" style="height: 238px; display: none;">
<div class="SD_7vnwWhO0KG80czzPb3 option-0 al-option">AL</div>
<div class="SD_7vnwWhO0KG80czzPb3 option-1 ak-option">AK</div>
<div class="SD_7vnwWhO0KG80czzPb3 option-2 as-option">AS</div>
<div class="SD_7vnwWhO0KG80czzPb3 option-3 az-option">AZ</div>
<div class="SD_7vnwWhO0KG80czzPb3 option-4 ar-option">AR</div>
<div class="SD_7vnwWhO0KG80czzPb3 option-5 ca-option">CA</div>
<div class="SD_7vnwWhO0KG80czzPb3 option-59 um-option">UM</div>
</div>

问题:自动化脚本使用硬编码的xpath语句定位相同的状态值(“CA”)(请参阅下面脚本中的代码片段) . 相反,我想使用名为“state”的存储变量来选择状态值 .

state_selection = self.driver.find_element_by_xpath("/html/body/div[2]/div/div[2]/div/div/div[2]/div[1]/form/div/div[2]/div[2]/div[3]/div[2]/div/div[3]/div[6]")
state_selection.click()

附加说明:我已尝试使用其他方法来定位状态值(见下文),但到目前为止,我只是成功使用上面的硬编码xpath .

我还尝试使用Selenium Select方法找到下拉元素,但我收到消息告诉我“选择仅适用于<select>元素,而不是'div'”

driver.findElement(by.xpath( “//选择[@ SD_7vnwWhO0KG80czzPb3 = ''] /选项[@值= 'CA']”)) . 单击()

1 回答

  • 0

    尝试按文本内容选择所需选项:

    state = "CA"
    state_selection = self.driver.find_element_by_xpath("//div[.='%s']" % state)
    state_selection.click()
    

相关问题