![](/img/trans.png)
[英]Encoding: TypeError: write() argument must be str, not bytes
[英]TypeError: can't concat bytes to str, then, TypeError: write() argument must be str, not bytes
最近在學習Python,正在嘗試做一個小練習。 然后出現此錯誤。
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
感謝幫助!!
試試這個: f.write(str(txt)+'\\n', 'utf-8') #or whichever way you are encoding
根據您的錯誤消息, write()
想要一個字符串,但您給它字節,因此,您必須調用str()
將 txt 轉換為 str 類型。
嘗試跟隨。 f.write(txt.decode()+'\\n')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.