首页 > 解决方案 > 遍历不同长度的列表

问题描述

我正在尝试遍历 CSV 中的 4 列,每列都包含不同数量的销售 ID。我制作了一个熊猫数据框并将每一行转换为一个列表。如果一列的销售 ID 数量多于以下列,则会出现错误:

消息:没有这样的元素:无法找到元素:{"method":"xpath","selector":"/html/body/form[1]/div/select/option[@value=nan]"}

但是,如果所有列都具有相同数量的 id,则代码可以正常工作。

    def get_report_data(self):
        current_date = helpers.currentDate
        data = pd.read_csv(r'C:\Users\rford\Desktop\sale_ids.csv')
        everyone_ids = data['Everyone'].tolist()
        dd_ids = data['Daily Deal'].tolist()
        targeted_ids = data['Targeted'].tolist()
        push_ids = data['Push Notification'].tolist()
        acq_ids = data['Acquisition'].tolist()
        for form_code, sales_type, idlist in (
        ( 1, "Everyone", everyone_ids ),
        ( 1, "Daily Deal", dd_ids ),
        ( 2, "Targeted", targeted_ids ),
        ( 2, "Push Notification", push_ids ),
        ( 2, "Acquisition", acq_ids ) ):
            print('Gathering {} Sale Information'.format(sales_type))
            for sale_id in idlist:
                results = []
                helpers.WebDriverWait(helpers.driver, 10)
                helpers.driver.find_element_by_xpath('/html/body/form[{}]/div/select/option[@value={}]'.format(form_code, sale_id)).click()

标签: pythonpandasseleniumoop

解决方案


内置函数any可能与每个列表的pop方法一起使用:

def get_report_data(self):
    current_date = helpers.currentDate
    data = pd.read_csv(r'C:\Users\rford\Desktop\sale_ids.csv')
    everyone_ids = data['Everyone'].tolist()
    dd_ids = data['Daily Deal'].tolist()
    targeted_ids = data['Targeted'].tolist()
    push_ids = data['Push Notification'].tolist()
    acq_ids = data['Acquisition'].tolist()
    for form_code, sales_type, idlist in (
    ( 1, "Everyone", everyone_ids ),
    ( 1, "Daily Deal", dd_ids ),
    ( 2, "Targeted", targeted_ids ),
    ( 2, "Push Notification", push_ids ),
    ( 2, "Acquisition", acq_ids ) ):
        print('Gathering {} Sale Information'.format(sales_type))
        while any(idlist):
            results = []
            helpers.WebDriverWait(helpers.driver, 10)
            helpers.driver.find_element_by_xpath(
                '/html/body/form[{}]/div/select/option[@value={}]'.format(
                    form_code, idlist.pop(0)
                )
            ).click()


推荐阅读