【问题标题】:BeautifulSoup, Python 3.3: UnicodeEncodeError for a string concatenationBeautifulSoup,Python 3.3:字符串连接的 UnicodeEncodeError
【发布时间】:2014-01-31 10:45:12
【问题描述】:

我是一名新手 Python 程序员,将在 Python 2.7 上运行的脚本转换为 Python 3.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 之间的行为差​​异。 任何启发表示赞赏。

【问题讨论】:

    标签: python python-3.x beautifulsoup


    【解决方案1】:

    只需删除代码中lnk.encode('utf-8').encode('utf-8') 部分即可。 .encode() 方法在 Python 2.8 中用于破解 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'
                                          )
    

    【讨论】:

      猜你喜欢
      • 2013-02-09
      • 1970-01-01
      • 2010-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-11
      • 2020-10-05
      • 1970-01-01
      相关资源
      最近更新 更多