Python 创建 cookie,然后使用 cookie 加载页面
我想从 python 程序访问网页。 我必须设置 cookie 才能加载页面。
我使用了 httplib2 库,但没有找到如何添加自己的 cookie
resp_headers, content = h.request("http://www.theURL.com", "GET")
如何创建具有正确名称和值的 cookie,将其添加到函数中然后加载页面?
谢谢
I would like to access a web page from a python program.
I have to set up cookies to load the page.
I used the httplib2 library, but I didn't find how add my own cookie
resp_headers, content = h.request("http://www.theURL.com", "GET")
How can I create cookies with the right name and value, add it to the function and then load the page?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自http://code.google.com/p/httplib2/wiki/Examples 希望会有所帮助 )
Cookies
当自动化某些操作时,您通常需要“登录”以维护与服务器的某种会话/状态。有时,这是通过基于表单的身份验证和 cookie 来实现的。您将一个表单发布到服务器,它会在传入的 HTTP 标头中使用 cookie 进行响应。您需要在后续请求中将此 cookie 传递回服务器以维护状态或保持会话处于活动状态。
以下是执行 HTTP Post 时如何处理 cookie 的示例。
首先,让我们导入我们将使用的模块:
现在,让我们定义我们需要的数据。在本例中,我们正在执行一个表单发布,其中包含两个表示用户名和密码的字段。
现在我们可以发送 HTTP 请求:
此时,我们的“response”变量包含服务器返回的 HTTP 标头字段的字典。如果返回 cookie,您将看到包含 cookie 值的“set-cookie”字段。我们想要获取这个值并将其放入后续请求的传出 HTTP 标头中:
现在我们可以使用此标头发送请求,它将包含 cookie,以便服务器可以识别我们。
所以...这是脚本中的全部内容。我们登录到一个站点,然后使用我们收到的 cookie 发出另一个请求:
From http://code.google.com/p/httplib2/wiki/Examples hope will help )
Cookies
When automating something, you often need to "login" to maintain some sort of session/state with the server. Sometimes this is achieved with form-based authentication and cookies. You post a form to the server, and it responds with a cookie in the incoming HTTP header. You need to pass this cookie back to the server in subsequent requests to maintain state or to keep a session alive.
Here is an example of how to deal with cookies when doing your HTTP Post.
First, lets import the modules we will use:
Now, lets define the data we will need. In this case, we are doing a form post with 2 fields representing a username and a password.
Now we can send the HTTP request:
At this point, our "response" variable contains a dictionary of HTTP header fields that were returned by the server. If a cookie was returned, you would see a "set-cookie" field containing the cookie value. We want to take this value and put it into the outgoing HTTP header for our subsequent requests:
Now we can send a request using this header and it will contain the cookie, so the server can recognize us.
So... here is the whole thing in a script. We login to a site and then make another request using the cookie we received:
您可能需要添加另一个标头参数来指定另一个 HTTP 请求参数。
You may want to add another header parameters to specify another HTTP request parameters.
您还可以仅使用 urllib2 库
You can also use just urllib2 library