Python爬虫如何处理弹框式的登录?
目前需要做一个后台管理系统的爬虫
不过这个后台管理系统,是弹出一个系统弹框,不是那种常规的 HTML 输入的登录方式。
如图:
我是用 requests 直接爬的,遇到这种弹框式的输入,不知如何下手。
求各位指教,多谢。
Python爬虫如何处理弹框式的登录?
9 回复
对于弹框式登录(通常是HTTP Basic/Digest认证),直接用requests库的auth参数处理就行。
import requests
from requests.auth import HTTPBasicAuth
# 直接使用HTTP Basic认证
response = requests.get(
'https://api.example.com/protected',
auth=HTTPBasicAuth('username', 'password')
)
# 或者更简洁的写法
response = requests.get(
'https://api.example.com/protected',
auth=('username', 'password') # requests会自动转为Basic认证
)
print(response.status_code)
print(response.text)
如果网站用的是Digest认证,换成HTTPDigestAuth:
from requests.auth import HTTPDigestAuth
response = requests.get(
'https://api.example.com/protected',
auth=HTTPDigestAuth('username', 'password')
)
有些网站会在首次请求返回401状态码,然后才弹出认证框。这时候需要处理401响应:
import requests
session = requests.Session()
url = 'https://api.example.com/protected'
# 先发个请求触发认证
initial_response = session.get(url)
if initial_response.status_code == 401:
# 添加认证信息后重试
session.auth = ('username', 'password')
final_response = session.get(url)
print(final_response.text)
else:
print(initial_response.text)
如果弹框是JavaScript生成的(比如用alert或自定义模态框),那就不是HTTP认证了,得用Selenium这类工具模拟浏览器操作:
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
import time
driver = webdriver.Chrome()
driver.get('https://example.com/login')
# 等弹框出现并输入信息
try:
username_input = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "username"))
)
password_input = driver.find_element(By.ID, "password")
username_input.send_keys("your_username")
password_input.send_keys("your_password")
# 提交登录表单
login_button = driver.find_element(By.ID, "login-btn")
login_button.click()
# 等页面加载完
time.sleep(2)
finally:
driver.quit()
先搞清楚弹框是HTTP认证还是JS弹窗,选对方法就行。
图挂了。。你常规的 HTML 登录方式时是怎么实现用脚本登录的, 在这里应该都一样。
这个是 HTTP Basic 认证,把用户名:密码 base64 请求协议头就可以。具体你搜索下那参数
做爬虫,前端页面不重要,只需要分析清楚了 http 交互逻辑即可。
#3 #4 正解
#3 #4 楼正解,如果你技术过硬,直接修改 Js, 让它无处可弹,略略路!
#3 #4 正解,多谢。


