尝试通过我的电脑上的Cookie发送发送请求来获取请求
#! /usr/bin/python
import re #regex
import urllib
import urllib2
#get request
x = urllib2.urlopen("http://www.example.com) #GET Request
cookies=x.headers['set-cookie'] #to get the cookies from get request
url = 'http://example' # to know the values type any password to know the cookies
values = {"username" : "admin",
"passwd" : password,
"lang" : "" ,
"option" : "com_login",
"task" : "login",
"return" : "aW5kZXgucGhw" }
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
result = response.read()
cookies=response.headers['set-cookie'] #to get the last cookies from post req in this variable
然后我在谷歌搜索
如何在同一个帖子请求中发送cookie并找到
opener = urllib2.build_opener() # send the cookies
opener.addheaders.append(('Cookie', cookies)) # send the cookies
f = opener.open("http://example")
但我不知道应该在我的代码中输入它
我需要做的就是
发送GET请求,将请求中的cookie放入变量,然后使用我从GET请求获得的值发出post请求
如果有人知道答案我需要编辑我的代码
答案 0 :(得分:2)
只需创建一个HTTP开启工具和一个cookiejar处理程序。因此,cookie将被检索并将自动一起传递给下一个请求。参见:
import urllib2 as net
import cookielib
import urllib
cookiejar = cookielib.CookieJar()
cookiejar.clear_session_cookies()
opener = net.build_opener(net.HTTPCookieProcessor(cookiejar))
data = urllib.urlencode(values)
request = net.Request(url, urllib.urlencode(data))
response = opener.open(request)
由于opener
是一个全局处理程序,只需发出任何请求,之前请求发送的先前cookie将自动出现在下一个请求(POST / GET)中。
答案 1 :(得分:0)
你应该真正研究python必须提供的请求库。您需要做的就是为您创建一个字典cookie键/值对,并将其作为一个arg传递。
您的整个代码可以替换为
#import requests
url = 'http://example' # to know the values type any password to know the cookies
values = {"username" : "admin",
"passwd" : password,
"lang" : "" ,
"option" : "com_login",
"task" : "login",
"return" : "aW5kZXgucGhw" }
session = requests.Session()
response = session.get(url, data=values)
cookies = session.cookies.get_dict()
response = reqeusts.post(url, data=values, cookies=cookies)
第二段代码可能就是你想要的,但取决于响应的格式。