python - 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 不这么认为。如果我只使用requests
withoutbs4
并从 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
解决方案
从评论讨论:
请在这种情况下找到两个字符串的类型。在这种特定情况下,一个是 Unicode 类型,另一个是字符串类型。将字符串类型转换为 Unicode,然后比较两个字符串有助于更快地解决问题。
快乐编码:) @uzdisral
推荐阅读
- python - 如果我的数据库已经手动设计,我是否需要使用 sqlalchemy?
- pandas - 大熊猫按排名连续日期分组
- database - 在 Windows 10 中通过 cmd 登录 postgreSQL 时遇到困难
- polymer - 如何在纸张按钮单击时导航到上一条路线?
- python - Python:无法从 API 打印不同的 JSON 响应
- html - 无法在 UL + LI (CSS) 中隐藏 HTML
- node.js - 确认付款已到达外部银行账户
- sql-server - 加入并更改显示值
- google-cloud-firestore - 在 Google FireStore 中保护和选择分层数据
- python - 如何更正错误 1 位置参数丢失,其中类实例是另一个类的实例的属性?