2017-09-26 41 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