Python请求 - 在同一页面上发送两个请求?

时间:2016-12-29 14:42:36

标签: python python-requests

我正在尝试更改网站上帐户的用户名。需要3个POST参数:

1)newName
2)密码
3)authenticityToken

每次加载页面时都会随机生成authenticityToken。隐藏输入类型:

<input type="hidden" name="authenticityToken" value="0640ce533fc7a51b88f79ce17cdbd611f4dc2360"/>

我想要实现的是获取authenticityToken的值,并在同一页面上POST上面所述的3个参数。目前,我的代码使用GET请求接收authenticityToken,然后发送另一个POST请求。它返回

  

不良真实性令牌

我目前使用的代码如下:

import requests
from bs4 import BeautifulSoup

url = "https://account.mojang.com"

#Login and save cookies
r = requests.post("https://account.mojang.com/login", data={'username':'theUsername','password':'thePassword','remember':'true'})
Logincookies = r.cookies

#Parse the page to get rename link
soup = BeautifulSoup(r.text, "html.parser")
renamePage = None
sources = soup.findAll('a',{"href":True})
for source in sources:
    if("/me/renameProfile/" in source["href"]):
       renamePage = source["href"]


#Get AuthToken

authToken = None
r = requests.get(url + renamePage,cookies=Logincookies)
parser = BeautifulSoup(r.text,"html.parser")
srcs = parser.findAll('input')
for src in srcs:
    if(src["name"] == "authenticityToken"):
        authToken = src["value"]
print(authToken)


r = requests.post(url + renamePage, cookies=Logincookies, data={'newName':'theNewUsername','password':'thePassword','authenticityToken':authToken})
print(r.text)

再次,我该如何做到这一点,以便GET和POST请求一起进行,以便它不使用新页面并接收新的authenticityToken?

2 个答案:

答案 0 :(得分:0)

尝试使用Session。它应该允许您在不同的请求中使用相同的cookies,访问令牌等:

s = requests.Session()
url = "https://account.mojang.com"
r = s.post("https://account.mojang.com/login", data={'username':'theUsername','password':'thePassword','remember':'true'})
Logincookies = r.cookies
...
r = s.get(url + renamePage,cookies=Logincookies)

P.S。在某些情况下,您可能还需要在headers中指定客户端,例如headers={ "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0" }

答案 1 :(得分:0)

因此,解决方案是使用名为RoboBrowser的库,并将其提供给我之前请求使用的相同会话:

import requests
from bs4 import BeautifulSoup
from robobrowser import RoboBrowser

session=requests.session()
r = session.post(...)
r = session.get("...")

browser.open(url+renamePage)
rename_form = browser.get_form(class_='standard')
rename_form['newName'].value = "theNewUser"
rename_form['password'].value = "theNewPass"

browser.submit_form(rename_form)