如何通过读取csv文件来选择下拉列表值

时间:2017-11-21 19:50:32

标签: python selenium drop-down-menu

我有一个包含State和city作为CSV文件的文件。

以下是一个示例CSV文件

routerLink

我有一个包含城市的下拉框。 请在下面的下拉列表中找到城市的格式,

ALABAMA,ANNISTON
ARIZONA,GLOBE

现在我想从csv文件中的下拉列表中选择城市。 这是我试过的,

ANNISTON (362)
GLOBE (385-480)

错误,因为在 csv文件中城市名称就像" ANNISTON" 但在下拉列表中它就像" ANNISTON(362)"

我希望在匹配期间删除下拉列表中的城市名称后面的数字。然后,只有cityname将从csv文件中与dropbox中的cityname匹配。

基本上我是在提取数据。 先谢谢你们。

1 个答案:

答案 0 :(得分:1)

很遗憾,您无法进行部分文本匹配或从字符串中删除数字。您可以做的是遍历可用选项,直到找到匹配项。也许是这样的:

...
# Grab the select box with selenium, same as you had before
cityid = Select(driver.find_element_by_id('Location_CityId'))

# Iterate through the available dropdown items
for option in cityid.options:
    # Grab the value of the current dropdown

    ### NOT USED -> This is for getting the option value, not the text
    # option_value = option.get_attribute('value')
    option_text = option.text

    # Check if the city you're currently looking for matches the current dropdown
    if City_Name in option_text:
        # If it does match, click on that item
        option.click()
        # Break out of the loop since we found what we're looking for
        break