我有一个for循环从网站获取数据,并想导出到xlsx或csv文件。通常,当我打印循环的结果时,我可以得到所有的列表,但是当我把它导出到xlsx文件时,我只能得到最后一项。问题出在哪里,你能帮上忙吗?
for item1 in spec:
spec2 = item1.find_all('th')
expl2 = item1.find_all('td')
spec2x = spec2[a].text
expl2x = expl2[a].text
yazim = spec2x + ': ' + expl2x
cumle = yazim
patern = r"(Brand|Series|Model|Operating System|CPU|Screen|MemoryStorage|Graphics Card|Video Memory|Dimensions|Screen Size|Touchscreen|Display Type|Resolution|GPU|Video Memory|Graphic Type|SSD|Bluetooth|USB)"
if re.search(patern, cumle):
speclist = translator.translate(cumle, lang_tgt='tr')
specl = speclist
#print(specl)
import pandas as pd
exp = [{ 'Prospec': specl,},]
df = pd.DataFrame(exp, columns = ['Prospec',])
df.to_excel('output1.xlsx',)发布于 2021-03-27 07:04:35
创建一个空列表,并在for循环中的每次迭代中,向该列表追加一个数据框。您最终将得到一个数据帧列表。在循环之后,使用pd.concat()通过连接列表中的每个元素来创建一个新的数据框。然后可以将生成的df保存到excel文件中。
您的代码将如下所示:
import pandas as pd
df_list = []
for item1 in spec:
......
if re.search(patern, cumle):
....
df_list.append(pd.DataFrame(.....))
df = pd.concat(df_list)
df.to_excel(.....)https://stackoverflow.com/questions/66824927
复制相似问题