Python:urllib / urllib2 / httplib混淆 [英] Python: urllib/urllib2/httplib confusion

查看:217
本文介绍了Python:urllib / urllib2 / httplib混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过在Python中编写登录序列脚本来测试Web应用程序的功能,但我遇到了一些麻烦。

I'm trying to test the functionality of a web app by scripting a login sequence in Python, but I'm having some troubles.

这就是我需要的东西要做的事情:

Here's what I need to do:


  1. 使用一些参数和标题进行POST。

  2. 遵循重定向

  3. 检索HTML正文。

现在,我对python相对较新,但是到目前为止,我测试过的两件事情都没有奏效。首先我使用了httplib,putrequest()(传递URL中的参数)和putheader()。这似乎没有遵循重定向。

Now, I'm relatively new to python, but the two things I've tested so far haven't worked. First I used httplib, with putrequest() (passing the parameters within the URL), and putheader(). This didn't seem to follow the redirects.

然后我尝试了urllib和urllib2,将标题和参数作为dicts传递。这似乎返回登录页面,而不是我试图登录的页面,我想这是因为缺少cookie或其他东西。

Then I tried urllib and urllib2, passing both headers and parameters as dicts. This seems to return the login page, instead of the page I'm trying to login to, I guess it's because of lack of cookies or something.

我错过了什么简单?

谢谢。

推荐答案

专注于 urllib2 为此,它运作良好。不要乱用 httplib ,它不是顶级API。

Focus on urllib2 for this, it works quite well. Don't mess with httplib, it's not the top-level API.

你注意到的是 urllib2 不遵循重定向。

What you're noting is that urllib2 doesn't follow the redirect.

您需要折叠的实例HTTPRedirectHandler 将捕获并跟踪重定向。

You need to fold in an instance of HTTPRedirectHandler that will catch and follow the redirects.

此外,您可能希望子类化默认的 HTTPRedirectHandler 捕获您将在单元测试中检查的信息。

Further, you may want to subclass the default HTTPRedirectHandler to capture information that you'll then check as part of your unit testing.

cookie_handler= urllib2.HTTPCookieProcessor( self.cookies )
redirect_handler= HTTPRedirectHandler()
opener = urllib2.build_opener(redirect_handler,cookie_handler)

然后你可以使用这个 opener 对象进行POST和GET,正确处理重定向和cookie。

You can then use this opener object to POST and GET, handling redirects and cookies properly.

您可能希望添加自己的 HTTPHandler 子类来捕获和记录各种错误代码。

You may want to add your own subclass of HTTPHandler to capture and log various error codes, also.

这篇关于Python:urllib / urllib2 / httplib混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆