机器人自动登录知乎网
```python
from selenium.webdriver import Chrome, By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import random
配置参数
ACCOUNTS = [
{"username": "备用账号1", "password": "密码1"},
{"username": "备用账号2", "password": "密码2"}
]
LOGIN_URL = "YOUR_LOGIN_URL_HERE" 请替换为实际的登录URL
DRIVER_PATH = "./chromedriver" ChromeDriver路径
def auto_login():
启动Chrome浏览器
driver = Chrome(DRIVER_PATH)
try:
打开登录页面
driver.get(LOGIN_URL)
随机选择一个账号
account = random.choice(ACCOUNTS)
输入账号密码
username_field = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.NAME, "username"))
)
username_field.send_keys(account["username"])
password_field = driver.find_element(By.NAME, "password")
password_field.send_keys(account["password"])
点击登录按钮
login_button = driver.find_element(By.XPATH, "//button[type='submit']")
login_button.click()
等待登录完成(可增加验证码处理逻辑)
time.sleep(random.uniform(2, 5))
保存Cookie到本地
with open("zhihu_cookies.txt", "w") as f:
f.write(str(driver.get_cookies()))
print("Cookie已保存至本地文件。") 提示用户操作成功信息,增强用户体验感。
except Exception as e: