最近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
感謝を試してみました!それゆえ、あなたはSTR型にTXTを変換するstr()
を呼び出す必要があり、f.write(str(txt)+'\n', 'utf-8') #or whichever way you are encoding
あなたのエラーメッセージから
、write()
は、文字列を望んでいるが、あなたはそれがバイト与えている:
なぜ 'i.text'をUTF-8にエンコードしていますか? 'txt'をエンコードしなければ、' str'オブジェクトになります。さらにデコードしなくても、より多くのテキストを連結して**、**テキストファイルに書き込むことができます。 –