写入.txt文件时出现TypeError Python

问题描述:

我正在从网站获取数据,并将其写入.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'错误。

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')