python - 在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
解决方案
至少对我来说,使用纯 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()
推荐阅读
- java - 迁移到 java 11 时注释不起作用
- visual-studio - 主源代码库和各种版本/客户
- css - 视频目录 CSS 和加载(嵌入式视频)
- mysql - MYSQL 两个内部连接不产生结果
- angular - 在 JWT 刷新时出现 401 时重定向
- python - Python3从txt文件中的URL下载csv文件
- html - XML 解析错误:格式不正确的“第 1 行,第 2 列”
- c# - POST 请求重定向,但是 AllowAutoRedirects = false 给出 302 异常,如何避免呢?
- python - TypeError:“PhotoImage”对象不可迭代
- python - 如何将默认参数添加到单击选项python