在针对Excel行循环的拆分中,我在做什么错?

时间:2019-06-17 06:34:37

标签: python excel openpyxl attributeerror nonetype

我写了这段小代码,从excel工作簿中的URL列表中拆分域。但是问题是我无法在实际工作簿中编写它,甚至无法创建具有域的新工作簿。

#looping it
for i in range(2, 200):
print((sheet.cell(row=i, column=1).value).split('http://')[-1].split('/')[0].split('www.')[-1])

#but by this i have to go copy paste the results in the excel sheet
#so i tried this replace value method but it keeps showing attribute error

for x in range(2, 258):
    sheet.cell(row=x, column=1).value = sheet.cell(row=x, column=1).value.split('http://')[-1].split('/')[0].split('www.')[-1]


Traceback (most recent call last):
  File "<pyshell#63>", line 2, in <module>
    sheet.cell(row=x, column=1).value = sheet.cell(row=x, column=1).value.split('http://')[-1].split('/')[0].split('www.')[-1]
AttributeError: 'NoneType' object has no attribute 'split'

我希望此循环遍历列表,并将网址(htts://www.example.com/example-page/)拆分为域(example.com),并在出现以下情况时将其保存在同一工作表或新工作表中一世     使用此

wb.save('domains_list')
#it saves the splitted domains automatically without me copy pasting it from idle to excel workbook.

1 个答案:

答案 0 :(得分:0)

就像评论中所说的那样,您必须处理单元格为空的情况:

for i in range(2, 200):
    val = sheet.cell(row=i, column=1).value
    if val is None:
        continue   
    print(val.split('http://')[-1].split('/')[0].split('www.')[-1])