2017-09-26 14 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、 )これを試して、動作しませんでした。 (r'C:\ Users \ Denis \ Desktop \ tempting texting \ {}。txt'.format(title)、 'w')もこれを試しても動作しませんでした。私は3.6.1を使用しています。 – denis2887