Python 请求从 GET 运行 JS 文件

Sup*_*tew 4 javascript python authentication python-requests python-requests-html

目标

使用 python requests 等登录此网站(https://www.reliant.com)(我知道这可以使用 selenium 或 PhantomJS 或其他东西来完成,但我不想这样做)

问题

在登录过程中,有几个重定向,其中传递“会话 ID”类型参数。其中大部分我都能得到,但有一个似乎dtPC来自您第一次访问该页面时获得的 cookie。据我所知,cookie源自这个JS文件(https://www.reliant.com/ruxitagentjs_ICA2QSVfhjqrux_10175190917092722.js)。该 url 是浏览器在主 url 的初始 GET 后执行的下一个 GET 请求。到目前为止我尝试过的所有方法都无法让我得到那个cookie。

到目前为止的代码

from requests_html import HTMLSession

url=r'https://www.reliant.com'
url2=r'https://www.reliant.com/ruxitagentjs_ICA2QSVfhjqrux_10175190917092722.js'
headers={
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
 'Accept-Encoding': 'gzip, deflate, br',
 'Accept-Language': 'en-US,en;q=0.9',
 'Cache-Control': 'max-age=0',
 'Connection': 'keep-alive',
 'Host': 'www.reliant.com',
 'Sec-Fetch-Mode': 'navigate',
 'Sec-Fetch-Site': 'none',
 'Sec-Fetch-User': '?1',
 'Upgrade-Insecure-Requests': '1',
 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.3'
}

headers2={
'Referer': 'https://www.reliant.com',
 'Sec-Fetch-Mode': 'no-cors',
 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'
}

s=HTMLSession()
r=s.get(url,headers=headers)
js=s.get(url2,headers=headers2).text

r.html.render() #works but doesn't get the cookie
r.html.render(script=js) #fails on Network error
Run Code Online (Sandbox Code Playgroud)

Sup*_*tew 5

好吧,我想通了,尽管它一直在与我作斗争。我不知道为什么dtPC没有以应有的方式出现s.cookies,但我没有script正确使用关键字。显然,无论你传递什么 JS,它都会在其他所有内容呈现后执行,就像你在浏览器上打开控制台并将其粘贴到那里一样。当我在 Chrome 中实际尝试时,我遇到了一些错误。最终我意识到我可以只运行一个简单的 JS 脚本来返回其他 JS 生成的 cookies。

s=HTMLSession()
r=s.get(url,headers=headers)
print(r.status_code)

c=r.html.render(script='document.cookie') 

c=urllib.parse.unquote(c)
c=[x.split('=') for x in c.split(';')]
c={x[0]:x[1] for x in c}
print(c)
Run Code Online (Sandbox Code Playgroud)

此时,将是一个带有键和相应值的c字典。'dtPC'