2017-03-07 121 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