配置环境
selenium安装:pip install selenium
chromedriver下载: http://chromedriver.storage.googleapis.com/index.html
注意:Chrome浏览器应与驱动版本对应
版本对应表:https://blog.csdn.net/L1542334210/article/details/101398105
代码正文
from selenium import webdriver
import time
def login():
#将py文件和chormedriver放在同一文件中
driver = webdriver.Chrome()
#driver = webdriver.Chrome(r'chormedriver所在地址')
name = '**********'#账号
password = '**********'#密码
try:
#将窗口最大化
driver.maximize_window()
#进入豆瓣登录界面
driver.get('https://accounts.douban.com/passport/login?source=movie')
#点击账号登陆
driver.find_element_by_xpath('//*[@id="account"]/div[2]/div[2]/div/div[1]/ul[1]/li[2]').click()
time.sleep(3)
print('正在输入用户名')
#清除输入框中默认的内容
driver.find_element_by_xpath('//*[@id="username"]').clear()
#传入账号
driver.find_element_by_xpath('//*[@id="username"]').send_keys(name)
time.sleep(2)
print('正在输入密码')
driver.find_element_by_xpath('//*[@id="password"]').clear()
#传入密码
driver.find_element_by_xpath('//*[@id="password"]').send_keys(password)
time.sleep(2)
#点击登陆按钮
driver.find_element_by_xpath('//*[@id="account"]/div[2]/div[2]/div/div[2]/div[1]/div[4]/a').click()
time.sleep(3)
print('登录成功')
time.sleep(3)
# 保存cookie,爬虫会用到
cookies = driver.get_cookies()
print(cookies)
time.sleep(4)
#退出驱动和网页
driver.quit()
except Exception as e:
print(e)
if __name__ == '__main__':
login()
过程简介
先利用查找功能,点击目标模块,对应的Element会提示出该模块所在具体位置,然后右键Copy→Copy Xpath即可获取标签所在位置,代码中最好要加入sleep,因为网页也需要时间加载
总结
selenium模拟登陆是比较全能的一种方法,也可以适用于其他网页,比如微博,但是上面的代码仅限于无需输入验证码的登陆,知乎就是行不通的,所以根据不同的网页代码内容需要进行相应的更改