BeautifulSoup,Python3.3:字符串连接的UnicodeEncodeError

2024-10-04 07:36:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个初级Python程序员,正在将运行在python2.7上的脚本转换为python3.3。我已经解决了一系列问题(urllib2等),现在我只能解决这个问题:

f.write(  soup.findAll(attrs={"class":"topictitle"})[x3].string.strip(' \t\n\r')  + ',' +
                                      inx + ',' +
                                      treadid + ',' +
                                      sid + ',' +
                                      link2.get('href') 
                                      + ',' 
                                      + "http://civicfbthailand.com/forum/" 
                                      + lnk.encode('utf-8')
                                      + '\n'
                                      )

返回:

Traceback (most recent call last):
 File "civicforum.py", line 73, in <module>
   + '\n'
TypeError: Can't convert 'bytes' object to str implicitly

第73行是列出的“+'\n'”但是我不明白为什么这个字符串不能连接,或者P27和P33之间的行为差异。 任何启迪都值得赞赏。你知道吗


Tags: 脚本stringurllib2attrsclasswrite程序员strip
1条回答
网友
1楼 · 发布于 2024-10-04 07:36:37

只需删除代码中.encode('utf-8')部分lnk.encode('utf-8')。在python2.8中使用.encode()方法来破解python2字符串是ASCII而Python3字符串是unicode这一事实,因此这种破解不再是必要的…而且不起作用;-)

f.write(  soup.findAll(attrs={"class":"topictitle"})[x3].string.strip(' \t\n\r')  + ',' +
                                      inx + ',' +
                                      treadid + ',' +
                                      sid + ',' +
                                      link2.get('href') 
                                      + ',' 
                                      + "http://civicfbthailand.com/forum/" 
                                      + lnk
                                      + '\n'
                                      )

相关问题 更多 >