首页 > 解决方案 > UnicodeWarning: Unicode 相等比较失败

问题描述

我不知道为什么我的两个字符串无法比较和匹配。

warn_msg = ('Přihlášení bylo neúspěšné.') # Translated as: Login Failed.

soup = BeautifulSoup(auth, 'lxml')
find_login = soup.find("div", class_="box").text # Will Give: 'Přihlášení bylo neúspěšné.'' # Translated as: 'Login Failed.'

"""
find_login returns: 'Přihlášení bylo neúspěšné.
"""

if find_login == warn_msg:
    print('Nothing')

当我将 bs4 字符串与我的 var 进行比较时,warn_msg它们是相等的,但 python 不这么认为。如果我只使用requestswithoutbs4并从 html 中切片解析的字符串并比较它们 = True。我很困惑为什么它似乎不适用于 bs4。我在这里查看了编码手册:https ://www.python.org/dev/peps/pep-0263/但我没有得到它的工作。

我得到的错误:

UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal

这只是我的工作示例,仅使用requests

for i in passwords:
    auth = requests.post(login_url, headers=headers, data=payload).content[7838:7872]
    if auth == warn_msg:
        print('It works, strings match')

输出:

C:\Users\petr>E:\Scripting\python\test.py
It works, strings match

标签: pythonstringbeautifulsouppython-unicode

解决方案


从评论讨论:

请在这种情况下找到两个字符串的类型。在这种特定情况下,一个是 Unicode 类型,另一个是字符串类型。将字符串类型转换为 Unicode,然后比较两个字符串有助于更快地解决问题。

快乐编码:) @uzdisral


推荐阅读