简体   繁体   English

python-requests cookie导出到硒

[英]python-requests cookies export to selenium

I want to login to website whit requests library and after export cookies to selenium, I'm write this code : 我想登录到网站whit请求库,然后将cookie导出到硒中,然后编写以下代码:

import requests
from selenium import webdriver

session=requests.Session()

MyHeaderss = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.32 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.32", "X-GWT-Permutation" : "6FEFBE57C6E73F0AB33BD5A4E17945DE", "Content-Type":"text/x-gwt-rpc; charset=utf-8"}

login_data = '''https://www.cartetitolari.mps.it/portaleTitolari/|FEAC78FFDF81D6121438D70986AF1C41|portale.titolari.client.service.PTService|login|portale.titolari.client.common.login.LoginRequest/3583069702|xxxxxxxxxxx|matteosbragia1984|'''


ra0=session.post('https://www.cartetitolari.mps.it/portaleTitolari/service', data=login_data, headers=MyHeaderss)
print ra0.content

profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.32 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.32")

driver = webdriver.Firefox()
driver.add_cookie(session.cookies.get_dict())

driver.get("https://www.cartetitolari.mps.it/portaleTitolari/downloadeco?id=0")

The code work, but not successfully export session/cookies in selenium, when the page loads are required to login! 当需要页面加载才能登录时,代码可以工作,但不能成功导出硒中的会话/ cookie! Where I'm wrong ? 我哪里错了?

You first need to navigate to the page to set the domain, then add each cookie by iterating the cookie jar: 您首先需要导航到页面来设置域,然后通过迭代cookie jar添加每个cookie:

driver.get("https://www.cartetitolari.mps.it/portaleTitolari/titolari.html")

for c in session.cookies :
    driver.add_cookie({'name': c.name, 'value': c.value, 'path': c.path, 'expiry': c.expires})

I had a similar issue. 我有一个类似的问题。 Watching with the developer window, I could see that after login a cookie was being sent but then the page via javascript or something else was redirecting before returning control to the program. 通过开发人员窗口观看,我可以看到登录后发送了Cookie,但是通过javascript或其他内容进行的页面正在重定向,然后将控制权返回给程序。 So, I was unable to get that cookie and save it off. 因此,我无法获取该cookie并将其保存下来。

After more research I realised that the program was starting with a clean session each time ( this answer helped a lot ) so the persistent cookies weren't persistent at all. 经过更多研究后,我意识到该程序每次都从一个干净的会话开始( 此答案很有帮助 ),因此持久性cookie根本不是持久性的。 It took further research, but giving selenium (via splinter) a profile to work with resolved my issue. 经过了进一步的研究,但是(通过碎片)为硒提供了解决方案,从而解决了我的问题。

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("user-data-dir=" + tdir + "/chrome-session")
chrome_options.add_argument("--profile-directory=Default")
with Browser('chrome', headless=True, options=chrome_options) as browser:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM