Python 从 GET 请求 运行 JS 文件

Python Requests run JS file from GET

目标

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

问题

在登录过程中有几个重定向,其中传递了 "session 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

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

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)

此时,c将是一个以'dtPC'为键和对应值的dict。