简体   繁体   English

使用硒python从下拉菜单中动态查找最高价值

[英]find top value dynamically from drop down menu using selenium python

I'm using Python with Selenium. 我在Selenium中使用Python。 I'm trying to automate an application in which i need to extract top value from a drop menu. 我正在尝试使我需要从下拉菜单中提取最高价值的应用程序自动化。 The values keep on changing so i cannot pass a static xpath to my selenium python code. 值不断变化,因此我无法将静态xpath传递给我的硒python代码。

I tried the following code but none of them working. 我尝试了以下代码,但没有一个起作用。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import Select
import selenium.webdriver.support.ui as UI
select=driver.find_element_by_xpath("//*[@id='code' and @name='Code1']")
for option in select.options:
    print(option.text,option.get_attribute('value'))

The idea is to find all the values and extract the top value. 想法是找到所有值并提取最高值。 When i print select.options I don't see anything. 当我打印select.options我什么也看不到。 I extracted the following HTML by inspecting the drop down menu. 我通过检查下拉菜单提取了以下HTML。

<select name="Code1" style="width:250px" class="code" id="code">
    <option value="Select Code">Select  Code</option>
    <option value="GGGSGSG:C">GGGSGSG:C</option>
    <option value="AHR060">AHR060--NORTH</option>
    <option value="AGSGGS">AGSGGS--PTSTTS</option>
    <option value="NANNAN">NANNAN--BTSTT</option>
</select>

Now the values keep changing so I cannot pass any specific value in xpath. 现在值不断变化,因此我无法在xpath中传递任何特定值。 I need to find all option values dynamically and pass the top one to a variable and using that variable call xpath and click the element. 我需要动态查找所有选项值,并将最上面的一个传递给变量,然后使用该变量调用xpath并单击该元素。

You can try the following to select the top element using index. 您可以尝试以下操作以使用索引选择顶部元素。

select = UI.Select(driver.find_element_by_xpath("//*[@id='code' and 
@name='Code1']"))
select.select_by_index(0) 

try this 尝试这个

from selenium.webdriver.support.select import Select as WebDriverSelect
select_element = WebDriverSelect(driver.find_element_by_xpath("//*[@id='code' and @name='Code1']"))
select_element.select_by_index(0)

Why not just use a css selector for the first value, something like: 为什么不将css选择器用作第一个值,例如:

select#code option + option

or xpath 或xpath

//select[@id='code']/option[2]

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

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