首页 > 解决方案 > 如何在网页上进行 POST 以使用 Python 的 selenium-requests 登录网站

问题描述

我必须登录一个网站(例如,我将使用 facebook.com)。我可以使用 selenium 管理登录过程,但我需要使用 POST 来完成。我尝试使用请求,但无法将所需的信息传递给 selenium webdriver,以便以登录用户身份进入站点。我在网上找到了一个集成 selenium 并请求https://pypi.org/project/selenium-requests/的库,但问题是没有文档,我在同一个故事中被阻止了。

使用硒请求

webdriver = Chrome()
url = "https://www.facebook.com"
webdriver.get(url)

params = {
    'email': 'my_email',
    'pass': 'my_password'
    }
resp = webdriver.request('POST','https://www.facebook.com/login/device-based/regular/login/?login_attempt=1&lwv=110', params) 

webdriver.get(url) 
# I hoped that the new page open was the one with me logged in but it did not works

使用 Selenium 和请求传递 cookie

driver = webdriver.Chrome()
webdriver = Chrome()
url = "https://www.facebook.com"
driver.get(url)

#storing the cookies generated by the browser
request_cookies_browser = driver.get_cookies()

#making a persistent connection using the requests library
params = {
    'email': 'my_email',
    'pass': 'my_password'
    }

s = requests.Session()
#passing the cookies generated from the browser to the session
c = [s.cookies.set(c['name'], c['value']) for c in request_cookies_browser]
resp = s.post('https://www.facebook.com/login/device-based/regular/login/?login_attempt=1&lwv=110', params) #I get a 200 status_code
#passing the cookie of the response to the browser
dict_resp_cookies = resp.cookies.get_dict()
response_cookies_browser = [{'name':name, 'value':value} for name, value in dict_resp_cookies.items()]
c = [driver.add_cookie(c) for c in response_cookies_browser]
driver.get(url)

在这两种情况下,如果最后我打印 cookie 似乎从一开始就发生了变化,但页面仍然是登录表单的页面。

这是我尝试过的代码,我尝试了两种尝试,但找到这两种方法之一就足够了。有人可以帮助我并知道我必须做什么或更改以在我登录的情况下打开页面吗?

先感谢您!

标签: pythonseleniumselenium-webdriverpython-requestsselenium-chromedriver

解决方案


我也有同样的问题。在您的代码中,您只需按原样传递参数。在此示例中,代码将data=params位于:

resp = webdriver.request('POST','https://www.facebook.com/login/device-based/regular/login/?login_attempt=1&lwv=110', params)

推荐阅读