Python unicode 字符串到字符串?

Python unicode string to string?

这会得到最后一个 div 的内容 class="title":

soup = BeautifulSoup(html)
title = soup.find_all('div', {'class' : 'title' })[-1].contents

当我 print(title) 它输出:

[u'Harry Potter']

我怎样才能打印出来:

Harry Potter

我尝试了 print(str(title)),但没有任何改变。

只需获取文本 使用get_text():

title = soup.find_all('div', {'class' : 'title' })[-1].get_text()

如果您更愿意转换 unicode 而不是像@alecxe 提到的那样获取字符串对象,则必须对其进行编码。

print(title.encode('utf-8')) 应该可以。如果您仍然得到方括号,只需执行 print(title[0].encode('utf-8'))