如何通过读取csv-fi来选择下拉值

2024-09-20 22:52:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含州和城市的CSV文件。在

这里有一个CSV文件示例

ALABAMA,ANNISTON
ARIZONA,GLOBE

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

^{pr2}$

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

with open("statecity.csv") as csvfile:
    csvreader = csv.reader(csvfile, delimiter=",")
    for line in csvreader:
        State_Name = line[0]
        City_Name = line[1]
        cityid = Select(driver.find_element_by_id('Location_CityId'))
        try:
            cityid.select_by_visible_text(City_Name)
            print City_Name +" " + "FOUND"
        except:
            print City_Name +" " + "NOT FOUND"

获取错误,因为在csv文件中,城市名称类似于“ANNISTON”,而在下拉列表中则类似于“ANNISTON(362)”

我想在匹配过程中删除下拉列表中城市名称后面的数字。然后,只有cityname将从csv文件中获得与dropbox中cityname相关的匹配。在

基本上是为了提取数据。 提前谢谢各位。在


Tags: 文件csvcsvfilename名称city列表by
1条回答
网友
1楼 · 发布于 2024-09-20 22:52:02

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

...
# 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

相关问题 更多 >

    热门问题