我无法获取 cookie,将其传递到我的参数列表,然后使用请求库发布该 cookie。
我用 Burpsuite 捕获了帖子,sessionId 是参数之一,请参见下面的屏幕截图。 http://imgur.com/OuRi4bI
网页的源代码在下面的截图中 http://imgur.com/TLTgCjc
我的代码如下:
import requests
import cookielib
import sys
from bs4 import BeautifulSoup
print "Enter the url",
url = raw_input
print url
r = requests.get(url)
c = r.content
soup = BeautifulSoup(c)
#Finding Captcha
div1 = soup.find('div', id='Custom')
comment = next(div1.children)
captcha = comment.partition(':')[-1].strip()
print captcha
#Finding viewstate
viewstate = soup.findAll("input", {"type" : "hidden", "name" : "__VIEWSTATE"})
v = viewstate[0]['value']
print v
#Finding eventvalidation
eventval = soup.findAll("input", {"type" : "hidden", "name" : "__EVENTVALIDATION"})
e = eventval[0]['value']
print e
# Get Cookie (this is where I am confused), and yes I have read through the Requests and BS docs
s = r.cookies
print s # Prints the class call but I don't get anything I can pass as a parameter
#Setting Parameters
params = {
'__VIEWSTATE' : v,
'txtMessage' : 'test',
'txtCaptcha' : captcha,
'cmdSubmit' : 'Submit',
'__EVENTVALIDATION' : e
#Need ASP.NET_SessionId Key : Value here
}
#Posting
requests.post(url, data=params)
print r.status_code
明确地说,当我连接到 Web 服务器时,我试图获取 sessionId 并将其用作发布到此留言板的参数。这是针对沙盒 VM 上的实验室,而不是实时站点。这是我第一次用 Python 写文章,所以如果我有错,我会尽我所能阅读 Lib 文档和其他网站。
谢谢!
请您参考如下方法:
将“s”作为参数传递给您的帖子。
s = r.cookies
print s # Prints the class call but I don't get anything I can pass as a parameter
您需要将 cookie 作为名为“cookies”的参数传递。 https://github.com/kennethreitz/requests/blob/master/requests/sessions.py中的源代码里面,它表示 cookie 可以是 CookieJar 或包含您要传递的 cookie 的字典。
在您的情况下,只需将您的 cookie 复制到下一篇文章会更容易,无需将它们转换为字典。
设置参数
params = {
'__VIEWSTATE' : v,
'txtMessage' : 'test',
'txtCaptcha' : captcha,
'cmdSubmit' : 'Submit',
'__EVENTVALIDATION' : e
#Need ASP.NET_SessionId Key : Value here
}
#Posting
requests.post(url, data=params,cookies=s)
但是,我强烈建议您使用 requests.Session() 对象。
session = requests.Session()
session.get(url)
session.get(url2)
#It will keep track of your cookies automatically for you, for every domain you use your session on . Very handy in deed, I rarely use requests.get unless I don't care at all about cookies.
