2017-03-07 120 views
0

最近學習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 

感謝您的幫助!

+1

爲什麼你將'i.text'編碼爲UTF-8?如果你不編碼'txt',它將是一個'str'對象,你可以連接更多的文本就好了,**和**把它寫入你的文本文件,而不必再次解碼。 –

回答

0

試試這個:f.write(str(txt)+'\n', 'utf-8') #or whichever way you are encoding

從你的錯誤信息,write()想要一個字符串,但你給它字節,因此,你必須調用str()到TXT文本轉換爲海峽型。

+1

能否詳細說明一下?你爲什麼認爲這是解決方案? – Matthias

+0

我很抱歉!這應該是足夠的解釋嗎? @Matthias – Priyank

+0

這解釋瞭如何擺脫錯誤,但問題的主要原因是,'txt'之前編碼爲UTF-8,沒有理由這樣做。 – Matthias