简体   繁体   English

python使用urllib2和cookielib进行身份验证,并获得登录通过/失败的结果

[英]python authenticate with urllib2 and cookielib and get login passed/failed result

Here is cut from my code which I use to login into the remote site. 这是我用来登录远程站点的代码的一部分。 My problem is that I don't know how to handle authentication pass/fail result. 我的问题是我不知道如何处理身份验证通过/失败结果。

def prepareLoginData(self):
    self.post_login_data = urllib.urlencode({
                                                'login': self.user,
                                                'password': self.password,
                                                'Login': 'Login'
                                                })
    return self.post_login_data

def prepareOpener(self):
    cj = cookielib.CookieJar()
    self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    for header in self.headers:
        self.opener.addheaders.append(header)
    return self.opener

Then I login like below: 然后我如下登录:

self.resp = self.opener.open(self.login_page, self.post_login_data)

and parse the response self.resp.read() to check if login passed with regular expression. 并解析响应self.resp.read()以检查登录名是否通过正则表达式传递。 How can I get login result based on cookie value? 如何获得基于cookie值的登录结果? or maybe there is another way? 也许还有另一种方法? When auth passed or failed the only thing I see in cj is SESSID which does not give info about auth result. 当身份验证通过或失败时,我在cj中看到的唯一东西是SESSID,它不提供有关身份验证结果的信息。

Thanks in advance! 提前致谢!

Maybe you can look at the source code of the returned page: In a lot of moderns websites, every xhtml element of the page has an id or a class or is child on an element with an id or a class, so i think you can use an xhtml parser like BeautifulSoup to extract error messages from the website. 也许您可以看一下返回页面的源代码:在许多现代网站中,页面的每个xhtml元素都有一个ID或一个类,或者是具有ID或类的元素上的子元素,因此我认为您可以使用BeautifulSoup之类的xhtml解析器从网站中提取错误消息。

BeautifulSoup is verry easy to learn and to use, so you'll probabilly find a solution, but if not, give me the url of the website, and i'll try to write a working code... BeautifulSoup非常易于学习和使用,因此您很可能会找到解决方案,但是如果没有,请给我网站的网址,然后我将尝试编写有效的代码...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM