如何解决遍历不同长度的列表
我正在尝试遍历 CSV 中的 4 列,每列都包含不同数量的销售 ID。 我制作了一个熊猫数据框并将每一行转换为一个列表。 如果某列的销售 ID 数量大于以下列,则会出现错误:
消息:没有这样的元素:无法定位元素:{"method":"xpath","selector":"/html/body/form[1]/div/select/option[@value=nan]" }
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 ),"Push Notification",push_ids ),"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()
解决方法
内置函数 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 ),"Push Notification",push_ids ),"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()
,
事实证明,pandas 正在将 csv 的一些单元格读取为浮点数。 修复最终是在我的数据帧上使用 .fillna(0),然后将每一列转换为一个列表,并使用 .astype(int) 将它们设为整数
HTML
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。