我正在从网站上获取数据,并将其写入.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
我尝试在谷歌上四处寻找,我在Python 2.x和Python 3.x之间的TypeError: 'str' does not have the buffer interface
中看到了很多字符串。我尝试在代码中实现其中的一些解决方案,但它仍然会出现'ResultSet'
错误。
答案 0 :(得分: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_data
的文字内容写入Output.txt
,则应执行以下操作:
with open('Output.txt', 'w') as f:
for item in g_data:
f.write(item.text + '\n')