首页 > 解决方案 > 在python中使用urllib3传递用户名和密码

问题描述

我正在尝试从以下页面获取 html 响应

https://ghrc.nsstc.nasa.gov/pub/lis/iss/data/science/nqc/nc/2020/0101/

当我在 chrome 中打开这个 url 时,我必须输入用户名和我在网站上拥有的帐户的密码

我想在 python 中使用 urllib3 传递这个用户名和密码,我当前的代码是

import urllib3

url = 'https://ghrc.nsstc.nasa.gov/pub/lis/iss/data/science/nqc/nc/2020/0101/'
username = ''
password = ''
data = {'Username': username, 'Password': password}

http = urllib3.PoolManager()
r = http.request('POST', url, data)
print(r.status)

print(r.data)

但是运行它仍然会给出登录页面的响应

我不确定我是否需要使用 cookie,或者如何确定需要将用户名和密码以什么格式传递给 url 才能成功登录并被带到指定的 url

标签: pythonurllib3

解决方案


至少对我来说,使用纯 POST 请求很难做到这一点。对于这样的项目,我会使用 Selenium

pip install selenium

从这里下载 Chrome 驱动程序: https ://sites.google.com/a/chromium.org/chromedriver/downloads

从下载的文件中,将 chromedriver.exe 文件复制到应用根目录。

这是登录https://ghrc.nsstc.nasa.gov/pub/lis/iss/data/science/nqc/nc/2020/0101/的代码

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
#create an instance of webdriver
driver = webdriver.Chrome()

#navigate to URL
driver.get("https://ghrc.nsstc.nasa.gov/pub/lis/iss/data/science/nqc/nc/2020/0101")

# username and password variable
username = 'my_username'
password = 'my_password'

#get the username and password fields by id and fill them
input_user = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'username')))
input_user.send_keys(username)
input_pwd = driver.find_element_by_id('password')
input_pwd.send_keys(password)
#click the login button
btn = driver.find_element_by_xpath('//input[@type="submit"]')
btn.click()

推荐阅读