2016-08-14 11 views
0

私はウェブサイトからデータを取り込み、それを.txtファイルに書き出しています。.txtファイルに書き込むときのタイプエラーPython

head = 'mpg123 -q ' 
tail = ' &' 

url = 'http://www.ndtv.com/article/list/top-stories/' 
r = requests.get(url) 
soup = BeautifulSoup(r.content) 

g_data = soup.find_all("div",{"class":"nstory_intro"}) 
log = open("/home/pi/logs/newslog.txt","w") 
soup = BeautifulSoup(g_data) 

# Will grab data from website, and write it to .txt file 
for item in g_data: 
     shorts = textwrap.wrap(item.text, 100) 
     text_file = open("Output.txt", "w") 
     text_file.write("%s" % g_data) 

     print 'Wrote Data Locally On Pi' 
     text_file.close() 

     for sentance in shorts: 
       print 'End.' 
    #    text_file = open("Output.txt", "w") 
    #    text_file.close() 

私はコンソールでそれを実行したときしかし、私はこのエラーを得続ける、ウェブサイトは、正しい情報を引き出し知っている:

TypeError: 'ResultSet' does not have the buffer interface 

私はGoogleで周りを探してみました、と私はPython 2.xとPython 3.xの間にあるTypeError: 'str' does not have the buffer interfaceの文字列では、このことがたくさんあります。私はコード内でこれらのソリューションのいくつかを実装しようとしましたが、それでもまだ'ResultSet'エラーが発生しています。

答えて

1

ResultSetはあなたのg_dataのタイプです:

In [8]: g_data = soup.find_all('div',{'class':'nstory_intro'}) 

In [9]: type(g_data) 
Out[9]: bs4.element.ResultSet 

あなたはより良い自動開閉を処理するためにcontext managerを使用しています。あなただけg_dataOutput.txtへのテキストの内容を書きたい場合は

、あなたはこれを行う必要があります。

with open('Output.txt', 'w') as f: 
    for item in g_data: 
     f.write(item.text + '\n') 
関連する問題