首页 > 解决方案 > 如何根据使用 selenium/python 的 Excel 工作表中给出的值从下拉列表中选择一个值

问题描述

我目前正在学习自动化一个包含下拉列表的 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: 'module' object is not callable

标签: pythonselenium-webdriverapache-poi

解决方案


您将需要使用Select 对象。首先,从您的 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))

推荐阅读