2017-04-07 64 views
0

我正在使用beautifulsoup來取消某些圖像鏈接。採用這種編碼,我設法讓他們都將聲明打印到變量中

images = [] 
images = page_soup.findAll('img') 

for image in images: 
    print(image.get('src')) 

現在我想的鏈接寫入到一個csv文件,有沒有辦法把我的print語句到一個變量,這樣它會寫入一個行?

這裏是我到目前爲止的代碼

with open('index.csv', 'a') as csv_file: 
    writer = csv.writer(csv_file) 
    writer.writerow([name, images, datetime.now()]) 

更新我改變了我的代碼

images = [] 
images = page_soup.findAll('img') 

with open('index.csv', 'a') as csv_file: 
    writer = csv.writer(csv_file) 
    for image in images: 
     writer.writerow([image.get_text(), image.get('src'), datetime.now()]) 

但仍具有CSV格式問題,我想所有的圖像鏈接到同一行打印。

enter image description here

+0

「這是我到目前爲止的代碼」 - 如果它不工作(這就是爲什麼你在這裏),而不是什麼發生? – hlt

回答

0

只是重構你的使用feteched的數據來填充你的CVS代碼。

像這可能是工作:

images = [] 
images = page_soup.findAll('img') 

with open('index.csv', 'a') as csv_file: 
    writer = csv.writer(csv_file) 
    for image in images: 
     writer.writerow([image.get_text(), image.get('src'), datetime.now()]) 
+0

非常感謝!它的工作,但它爲每個圖像鏈接做了一個新的行,並與每個圖像鏈接重複所有其他刮取的數據。而不是我所喜歡的,這是所有鏈接在一行中。 – user1663590

+0

這是因爲,在open('index.csv','a')'中有附加標誌設置。如果你想要擦除遺囑,只需用寫入標誌將其打開即可。 和你在一行中的含義是什麼?你想讓他們分開昏迷嗎?只是舉例適合您的要求的行 –

+0

謝謝您再次回覆我。我張貼了我想如何格式化csv的圖像 – user1663590