[英]TypeError when writing to .txt file Python
我正在從網站上獲取數據,並將其寫入.txt文件。
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上四處查看,對於TypeError: 'str' does not have the buffer interface
字符串,我TypeError: 'str' does not have the buffer interface
看到它TypeError: 'str' 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
您最好使用上下文管理器來自動處理打開和關閉。
如果只想將g_data
文本內容寫入Output.txt
,則應執行以下操作:
with open('Output.txt', 'w') as f:
for item in g_data:
f.write(item.text + '\n')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.