2017-09-26 44 views
0

我想美麗的湯,我想將它導出到文本文件。美麗的湯 - 導出到文本文件

如何將result.txt文件名改爲soup.find(class_="entry-title").get_text()的文本?

在此先感謝。

from bs4 import BeautifulSoup as bs 
import urllib.request 

#getting the page. 
url = urllib.request.urlopen('http://www.haripuisi.com/arsip/3163').read() 
soup = bs(url, 'lxml') 

#extracting the content. 
print (soup.find(class_="entry-title").get_text()) 
print (soup.find(class_="entry-content").get_text()) 

#save into text file. 
save_file = open(r'C:\Users\Denis\Desktop\tempting texting\result.txt', 'w') 
save_file.write(soup.find(class_="entry-content").get_text()) 
save_file.close() 
+1

什麼問題都你面對這個解決方案? –

+0

發現問題。必須將標題中的「:」字符替換爲另一個字符,以便保存文件。 – denis2887

回答

0
filename= soup.find(class_="entry-title").get_text()+".txt" 
save_file = open(filename, 'w+') 
save_file.close() 
0

試試這個代碼,我使用python2.7,所以你需要波紋管改變的東西:

from bs4 import BeautifulSoup as bs 
import urllib 


url = urllib.urlopen('http://www.haripuisi.com/arsip/3163').read() 
soup = bs(url, 'lxml') 
print (soup.find(class_="entry-title").get_text()) 
print (soup.find(class_="entry-content").get_text()) 

file_name= soup.find(class_="entry-title").get_text() 

save_file = open("/Users/luowensheng/Desktop/%s.txt"%file_name, "w") 
save_file.write(soup.find(class_="entry-content").get_text()) 
save_file.close() 

我得到的文件: enter image description here

+0

謝謝,我完全忘了如何操作字符串。 :) – denis2887

+0

我已經將條目標題重命名爲「title」,然後將代碼更改爲:open(r'C:\ Users \ Denis \ Desktop \ tempting texting \%s.txt'%title,'w' )試過這個,沒有工作。 open(r'C:\ Users \ Denis \ Desktop \ tempting texting \ {} .txt'.format(title),'w')也試過了,沒有用。我正在使用3.6.1。 – denis2887