Python:如何在Requests_HTML中添加NTLM身份验证?
使用requests_html传入认证与证书的GET请求改造
requests_html的HTMLSession继承自requests.Session,因此可以直接复用requests的认证、证书相关参数来改造你的代码:
修改后的完整代码
from requests.auth import HTTPBasicAuth import logging from requests_html import HTMLSession def get_url(url, auth_obj, cert_path): s = HTMLSession() try: # 传入认证对象与证书文件路径 response = s.get(url, auth=auth_obj, verify=cert_path) response.raise_for_status() # 触发HTTP状态码异常 except Exception as e: logging.exception('Could not send get request: {}'.format(e)) return None try: response.html.render() except Exception as e: logging.exception('Could not render HTML content: {}'.format(e)) return response
关键说明
- 认证对象传递:
auth参数可接受requests.auth模块下的各类认证实例,比如基础认证可用HTTPBasicAuth("用户名", "密码"),也可以传入自定义的认证类对象 - 证书路径设置:
verify参数直接传入本地证书文件的路径(如"./server_cert.pem"),如果是证书目录则传入目录路径 - 异常处理优化:新增
response.raise_for_status()捕获HTTP错误(4xx/5xx状态码),同时在请求异常时返回None,避免后续访问response属性报错 - 渲染异常防护:将
html.render()也包裹在异常处理中,防止渲染JS内容失败导致程序终止
内容的提问来源于stack exchange,提问作者stirfryp4pi
相关产品推荐
相关产品推荐

