如何使用Selenium / python根据Excel工作表中给出的值从下拉列表中选择一个值

时间:2019-07-04 12:25:59

标签: python selenium-webdriver apache-poi

我目前正在学习自动化包含下拉列表的Web应用程序。事情是能够通过直接在xpath中提供它来从下拉列表中选择值。现在我正在尝试从下拉列表中选择一个值是根据excel工作表中给出的值而不是直接给出的。我不知道该怎么做。

请找到示例HTML

<select class="parent" id="parent_name" name="parentId">                                      
  <option value="1">A</option>
  <option value="2">B</option>
  <option value="3">C</option>
  </select>

请找到我尝试添加的代码

dropdown=driver.find_element_by_xpath('//select[@class="parent"]//option[2]');
dropdown.click();

为了从excel中为其他值(例如文本框)选择值,我正在使用以下代码

driver = webdriver.Chrome  
driver.fullscreen_window();
driver.get('url');
time.sleep(5) 
Workbook=xlrd.open_workbook("excel path")
Details = Workbook.sheet_by_index(0);
city=Details .cell(1,0)
Citytextbox=driver.find_element_by_xpath('//input[@id="city"]');
Citytextbox.send_keys(city.value);

我期望的是,如果我在excel中将值赋予为“ A”,它应该能够从下拉列表中进行选择,而不是对其进行硬编码 我正在使用spyder-python 3.7。

更新:我尝试了以下两种方法来面对以下问题。您能否指导我解决可能的问题。 第一种方法似乎正在发生,即使选择了下拉菜单,代码仍在运行,并且未显示任何错误。看来它没有出现在代码中

 class test:
        def test(self):
           type=details.cell(1,13);
    dropdown=selected(self.driver.find_element_by_xpath('//select[@class="parent"]')); 
               dropdown.select_by_value(str(type));
               time.sleep(5);

第二种方法:它显示-module'对象不可调用。已添加导入选择为选中状态

type=details.cell(1,13);
dropdown=selected(driver.find_element_by_xpath('//select[@class="parent"]'));
dropdown.select_by_value(str(type));

当我通过上述方法尝试时,出现此错误 TypeError:“模块”对象不可调用

1 个答案:

答案 0 :(得分:0)

您将要使用Select object。首先,从Excel文档中提取相关值(您需要对以下内容进行调整以定位相关单元格,我根据您的问题提供了一个示例):

Workbook = xlrd.open_workbook("excel path")
Details = Workbook.sheet_by_index(0);
selectValue = Details .cell(1,0)

然后您将需要使用如下所示的值:

select = Select(self.driver.find_element_by_id("parent_name")) 
select.select_by_value(str(selectValue))