python-3.x - Python: Why does the variable appear to match the string, but the output says otherwise
问题描述
I'm making a simple script that checks to see if a user exit on a forum.
def xenforo_check():
url = "http://dfkitcar.com/forum/index.php?login/login"
name = "JSATX"
headers = {'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Encoding':'gzip, deflate', 'Content-Type':'application/x-www-form-urlencoded'}
payload = {'login':name}
response = requests.post(url, data=payload)
soup = BeautifulSoup(response.text, "html.parser")
name_result = soup.find("div", class_="blockMessage blockMessage--error blockMessage--iconic").text
if name_result == "Incorrect password. Please try again.":
print("user found")
elif name_result == "The requested user '"+name+"' could not be found.":
print("user not found")
else:
print("possible error")
print(name_result)
xenforo_check()
For this example the user does exist, so it should print "user found". Instead the output is:
possible error
Incorrect password. Please try again.
It seems to me that name_result is the same as "Incorrect password. Please try again." so I would expect it to print "user found".
The same thing has if I test a name that doesn't exit. The variable name_result doesn't equal the string. Why is this so?
解决方案
你是对的,name_result
似乎是一样的,但在测试它进行比较之前,print
它的内容并看看它真正的样子:
>>> print(name_result)
u'\nIncorrect password. Please try again.\n'
所以它实际上是一个unicode
包含不可见字符的字符串,即换行符' \n
',这是它真正比较的对象,因此它不匹配。
但是,如果我们strip()
从 中获取这些换行符text
,您应该会得到预期的输出,所以添加strip()
到这一行:
name_result = soup.find("div", class_="blockMessage blockMessage--error blockMessage--iconic").text.strip()
推荐阅读
- google-cloud-platform - 访问在 GCP VM 实例上运行的 jupyter notebook
- javascript - 如果一段时间未收到 websocket,则刷新页面
- java - 通过 JDBC 处理数据库时如何处理夏令时?
- azure - microsoft bot(使用 SDK for nlp with dispatch 创建)在部署到 Azure 后返回 401 未经授权的错误
- android - 找不到方法 'org.gradle.api.tasks.compile.CompileOptions.setBootClasspath(Ljava/lang/String;)V'
- python - 如何在熊猫数据框上应用范围查找?
- java - 如何在 spring-integration tcp 网关中实现粘性会话?
- apache-kafka - 消费者:如果中间件失去与外部应用程序的连接,则再次发送偏移量
- arrays - XWPFDocument 可以在不先将其保存到文件的情况下转换为 Byte[] 吗?
- python - ModuleNotFoundError:没有名为“jmespath”的模块