首页 > 解决方案 > 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?

标签: python-3.xbeautifulsouppython-requests

解决方案


你是对的,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()

推荐阅读