最近学习Python,我试图做一个小练习。然后出现这个错误。TypeError:无法将字节转换为str,然后TypeError:write()参数必须是str,而不是字节
File "/Users/Alexis/.spyder-py3/temp.py", line 29, in <module>
f.write(txt+'\n')
TypeError: can't concat bytes to str
有人能告诉我这里发生了什么事吗?
import requests
from bs4 import BeautifulSoup
import re
r=requests.get(url='http://news.qq.com/world_index.shtml')
soup=BeautifulSoup(r.text,'lxml')
f=open('/Users/Alexis/Desktop/news.text','w')
f.seek(0)
f.write('Today News')
news=soup.find_all('a',href=re.compile('http://news.qq.com/a/20170307/'))
for i in news:
txt=i.text.encode('utf-8').strip()
if txt=='':
continue
else:
u=i.attrs['href']
ur=requests.get(url=u)
usoup=BeautifulSoup(ur.text,'lxml')
f.write(txt+'\n')
f.write('Text:\n')
p=usoup.find('div',id='Cnt-Main-Article-QQ').find_all('p')
for i in p:
f.write(i.text+'\n')
break
f.close()
print('Finish')
我已经尝试了几种不同的方法
我已经试过
f.write(txt+'\n'.encode('ascii'))
TypeError: write() argument must be str, not bytes
f.write(txt+'\n'.encode('utf-8'))
TypeError: write() argument must be str, not bytes
TypeError: write() argument must be str, not bytes
感谢您的帮助!
为什么你将'i.text'编码为UTF-8?如果你不编码'txt',它将是一个'str'对象,你可以连接更多的文本就好了,**和**把它写入你的文本文件,而不必再次解码。 –