2016-08-14 128 views
0

我正在從網站獲取數據,並將其寫入.txt文件。寫入.txt文件時出現TypeError 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 

我試着在谷歌環顧四周,我在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')