javascript - Python 请求从 GET 运行 JS 文件

标签 javascript python authentication python-requests python-requests-html

目标

使用 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 脚本来返回其他 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。

关于javascript - Python 请求从 GET 运行 JS 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58121164/

相关文章:

python - 计数显示为 NaN

php - Laravel 5.2 使 :auth

c# - ServiceStack Redis Mq认证

Javascript - 从数组中提取随机字符串并得到未定义

javascript - 什么时候应该使用div?什么时候应该使用框架?我什么时候应该使用其他形式的动态内容?

javascript - 使用 createTextNode 插入文本

python - 为什么说模块pygame没有init成员?

python - 在 Django 中抛出自定义异常时异常值字段为空

javascript - 当脚本执行时 AJAX 调用返回时,JavaScript 会发生什么?

angular - 使用 Auth0 在 Angular 4 应用程序中注销时出现问题